Hmjz100 oniati commited on
Commit
c01d9cd
0 Parent(s):

Duplicate from oniati/mrt

Browse files

Co-authored-by: wu <[email protected]>

Files changed (6) hide show
  1. .gitattributes +31 -0
  2. README.md +31 -0
  3. app.py +305 -0
  4. download.wav +0 -0
  5. packages.txt +4 -0
  6. requirements.txt +19 -0
.gitattributes ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.model filter=lfs diff=lfs merge=lfs -text
11
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
12
+ *.npy filter=lfs diff=lfs merge=lfs -text
13
+ *.npz filter=lfs diff=lfs merge=lfs -text
14
+ *.onnx filter=lfs diff=lfs merge=lfs -text
15
+ *.ot filter=lfs diff=lfs merge=lfs -text
16
+ *.parquet filter=lfs diff=lfs merge=lfs -text
17
+ *.pickle filter=lfs diff=lfs merge=lfs -text
18
+ *.pkl filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pt filter=lfs diff=lfs merge=lfs -text
21
+ *.pth filter=lfs diff=lfs merge=lfs -text
22
+ *.rar filter=lfs diff=lfs merge=lfs -text
23
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
25
+ *.tflite filter=lfs diff=lfs merge=lfs -text
26
+ *.tgz filter=lfs diff=lfs merge=lfs -text
27
+ *.wasm filter=lfs diff=lfs merge=lfs -text
28
+ *.xz 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
README.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: MT3
3
+ emoji: 🦀
4
+ colorFrom: red
5
+ colorTo: green
6
+ sdk: gradio
7
+ app_file: app.py
8
+ pinned: false
9
+ duplicated_from: oniati/mrt
10
+ ---
11
+ # Configuration
12
+ `title`: _string_
13
+ Display title for the Space
14
+ `emoji`: _string_
15
+ Space emoji (emoji-only character allowed)
16
+ `colorFrom`: _string_
17
+ Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
18
+ `colorTo`: _string_
19
+ Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
20
+ `sdk`: _string_
21
+ Can be either `gradio` or `streamlit`
22
+ `sdk_version` : _string_
23
+ Only applicable for `streamlit` SDK.
24
+ See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions.
25
+
26
+ `app_file`: _string_
27
+ Path to your main application file (which contains either `gradio` or `streamlit` Python code).
28
+ Path is relative to the root of the repository.
29
+
30
+ `pinned`: _boolean_
31
+ Whether the Space stays on top of your list.
app.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
8
+
9
+ os.system("git clone --branch=main https://github.com/google-research/t5x")
10
+ os.system("mv t5x t5x_tmp; mv t5x_tmp/* .; rm -r t5x_tmp")
11
+ os.system("sed -i 's:jax\[tpu\]:jax:' setup.py")
12
+ 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
+ # copy checkpoints
23
+ os.system("gsutil -q -m cp -r gs://mt3/checkpoints .")
24
+
25
+ # copy soundfont (originally from https://sites.google.com/site/soundfonts4u)
26
+ os.system("gsutil -q -m cp gs://magentadata/soundfonts/SGM-v2.01-Sal-Guit-Bass-V1.3.sf2 .")
27
+
28
+ #@title Imports and Definitions
29
+
30
+
31
+
32
+
33
+
34
+ import functools
35
+ import os
36
+
37
+ import numpy as np
38
+
39
+ import tensorflow.compat.v2 as tf
40
+
41
+ import functools
42
+ import gin
43
+ import jax
44
+ import librosa
45
+ import note_seq
46
+
47
+
48
+
49
+ import seqio
50
+ import t5
51
+ import t5x
52
+
53
+ from mt3 import metrics_utils
54
+ from mt3 import models
55
+ from mt3 import network
56
+ from mt3 import note_sequences
57
+ from mt3 import preprocessors
58
+ from mt3 import spectrograms
59
+ from mt3 import vocabularies
60
+
61
+
62
+ import nest_asyncio
63
+ nest_asyncio.apply()
64
+
65
+ SAMPLE_RATE = 16000
66
+ SF2_PATH = 'SGM-v2.01-Sal-Guit-Bass-V1.3.sf2'
67
+
68
+ def upload_audio(audio, sample_rate):
69
+ return note_seq.audio_io.wav_data_to_samples_librosa(
70
+ audio, sample_rate=sample_rate)
71
+
72
+
73
+
74
+ class InferenceModel(object):
75
+ """Wrapper of T5X model for music transcription."""
76
+
77
+ def __init__(self, checkpoint_path, model_type='mt3'):
78
+
79
+ # Model Constants.
80
+ if model_type == 'ismir2021':
81
+ num_velocity_bins = 127
82
+ self.encoding_spec = note_sequences.NoteEncodingSpec
83
+ self.inputs_length = 512
84
+ elif model_type == 'mt3':
85
+ num_velocity_bins = 1
86
+ self.encoding_spec = note_sequences.NoteEncodingWithTiesSpec
87
+ self.inputs_length = 256
88
+ else:
89
+ raise ValueError('unknown model_type: %s' % model_type)
90
+
91
+ gin_files = ['/home/user/app/mt3/gin/model.gin',
92
+ '/home/user/app/mt3/gin/mt3.gin']
93
+
94
+ self.batch_size = 8
95
+ self.outputs_length = 1024
96
+ self.sequence_length = {'inputs': self.inputs_length,
97
+ 'targets': self.outputs_length}
98
+
99
+ self.partitioner = t5x.partitioning.PjitPartitioner(
100
+ model_parallel_submesh=None, num_partitions=1)
101
+
102
+ # Build Codecs and Vocabularies.
103
+ self.spectrogram_config = spectrograms.SpectrogramConfig()
104
+ self.codec = vocabularies.build_codec(
105
+ vocab_config=vocabularies.VocabularyConfig(
106
+ num_velocity_bins=num_velocity_bins))
107
+ self.vocabulary = vocabularies.vocabulary_from_codec(self.codec)
108
+ self.output_features = {
109
+ 'inputs': seqio.ContinuousFeature(dtype=tf.float32, rank=2),
110
+ 'targets': seqio.Feature(vocabulary=self.vocabulary),
111
+ }
112
+
113
+ # Create a T5X model.
114
+ self._parse_gin(gin_files)
115
+ self.model = self._load_model()
116
+
117
+ # Restore from checkpoint.
118
+ self.restore_from_checkpoint(checkpoint_path)
119
+
120
+ @property
121
+ def input_shapes(self):
122
+ return {
123
+ 'encoder_input_tokens': (self.batch_size, self.inputs_length),
124
+ 'decoder_input_tokens': (self.batch_size, self.outputs_length)
125
+ }
126
+
127
+ def _parse_gin(self, gin_files):
128
+ """Parse gin files used to train the model."""
129
+ gin_bindings = [
130
+ 'from __gin__ import dynamic_registration',
131
+ 'from mt3 import vocabularies',
132
133
+ 'vocabularies.VocabularyConfig.num_velocity_bins=%NUM_VELOCITY_BINS'
134
+ ]
135
+ with gin.unlock_config():
136
+ gin.parse_config_files_and_bindings(
137
+ gin_files, gin_bindings, finalize_config=False)
138
+
139
+ def _load_model(self):
140
+ """Load up a T5X `Model` after parsing training gin config."""
141
+ model_config = gin.get_configurable(network.T5Config)()
142
+ module = network.Transformer(config=model_config)
143
+ return models.ContinuousInputsEncoderDecoderModel(
144
+ module=module,
145
+ input_vocabulary=self.output_features['inputs'].vocabulary,
146
+ output_vocabulary=self.output_features['targets'].vocabulary,
147
+ optimizer_def=t5x.adafactor.Adafactor(decay_rate=0.8, step_offset=0),
148
+ input_depth=spectrograms.input_depth(self.spectrogram_config))
149
+
150
+
151
+ def restore_from_checkpoint(self, checkpoint_path):
152
+ """Restore training state from checkpoint, resets self._predict_fn()."""
153
+ train_state_initializer = t5x.utils.TrainStateInitializer(
154
+ optimizer_def=self.model.optimizer_def,
155
+ init_fn=self.model.get_initial_variables,
156
+ input_shapes=self.input_shapes,
157
+ partitioner=self.partitioner)
158
+
159
+ restore_checkpoint_cfg = t5x.utils.RestoreCheckpointConfig(
160
+ path=checkpoint_path, mode='specific', dtype='float32')
161
+
162
+ train_state_axes = train_state_initializer.train_state_axes
163
+ self._predict_fn = self._get_predict_fn(train_state_axes)
164
+ self._train_state = train_state_initializer.from_checkpoint_or_scratch(
165
+ [restore_checkpoint_cfg], init_rng=jax.random.PRNGKey(0))
166
+
167
+ @functools.lru_cache()
168
+ def _get_predict_fn(self, train_state_axes):
169
+ """Generate a partitioned prediction function for decoding."""
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})
173
+ return self.partitioner.partition(
174
+ partial_predict_fn,
175
+ in_axis_resources=(
176
+ train_state_axes.params,
177
+ t5x.partitioning.PartitionSpec('data',), None),
178
+ out_axis_resources=t5x.partitioning.PartitionSpec('data',)
179
+ )
180
+
181
+ def predict_tokens(self, batch, seed=0):
182
+ """Predict tokens from preprocessed dataset batch."""
183
+ prediction, _ = self._predict_fn(
184
+ self._train_state.params, batch, jax.random.PRNGKey(seed))
185
+ return self.vocabulary.decode_tf(prediction).numpy()
186
+
187
+ def __call__(self, audio):
188
+ """Infer note sequence from audio samples.
189
+
190
+ Args:
191
+ audio: 1-d numpy array of audio samples (16kHz) for a single example.
192
+ Returns:
193
+ A note_sequence of the transcribed audio.
194
+ """
195
+ ds = self.audio_to_dataset(audio)
196
+ ds = self.preprocess(ds)
197
+
198
+ model_ds = self.model.FEATURE_CONVERTER_CLS(pack=False)(
199
+ ds, task_feature_lengths=self.sequence_length)
200
+ model_ds = model_ds.batch(self.batch_size)
201
+
202
+ inferences = (tokens for batch in model_ds.as_numpy_iterator()
203
+ for tokens in self.predict_tokens(batch))
204
+
205
+ predictions = []
206
+ for example, tokens in zip(ds.as_numpy_iterator(), inferences):
207
+ predictions.append(self.postprocess(tokens, example))
208
+
209
+ result = metrics_utils.event_predictions_to_ns(
210
+ predictions, codec=self.codec, encoding_spec=self.encoding_spec)
211
+ return result['est_ns']
212
+
213
+ def audio_to_dataset(self, audio):
214
+ """Create a TF Dataset of spectrograms from input audio."""
215
+ frames, frame_times = self._audio_to_frames(audio)
216
+ return tf.data.Dataset.from_tensors({
217
+ 'inputs': frames,
218
+ 'input_times': frame_times,
219
+ })
220
+
221
+ def _audio_to_frames(self, audio):
222
+ """Compute spectrogram frames from audio."""
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')
226
+ frames = spectrograms.split_audio(audio, self.spectrogram_config)
227
+ num_frames = len(audio) // frame_size
228
+ times = np.arange(num_frames) / self.spectrogram_config.frames_per_second
229
+ return frames, times
230
+
231
+ def preprocess(self, ds):
232
+ pp_chain = [
233
+ functools.partial(
234
+ t5.data.preprocessors.split_tokens_to_inputs_length,
235
+ sequence_length=self.sequence_length,
236
+ output_features=self.output_features,
237
+ feature_key='inputs',
238
+ additional_feature_keys=['input_times']),
239
+ # Cache occurs here during training.
240
+ preprocessors.add_dummy_targets,
241
+ functools.partial(
242
+ preprocessors.compute_spectrograms,
243
+ spectrogram_config=self.spectrogram_config)
244
+ ]
245
+ for pp in pp_chain:
246
+ ds = pp(ds)
247
+ return ds
248
+
249
+ def postprocess(self, tokens, example):
250
+ tokens = self._trim_eos(tokens)
251
+ start_time = example['input_times'][0]
252
+ # Round down to nearest symbolic token step.
253
+ start_time -= start_time % (1 / self.codec.steps_per_second)
254
+ return {
255
+ 'est_tokens': tokens,
256
+ 'start_time': start_time,
257
+ # Internal MT3 code expects raw inputs, not used here.
258
+ 'raw_inputs': []
259
+ }
260
+
261
+ @staticmethod
262
+ def _trim_eos(tokens):
263
+ tokens = np.array(tokens, np.int32)
264
+ if vocabularies.DECODED_EOS_ID in tokens:
265
+ tokens = tokens[:np.argmax(tokens == vocabularies.DECODED_EOS_ID)]
266
+ return tokens
267
+
268
+
269
+
270
+
271
+
272
+
273
+ inference_model = InferenceModel('/home/user/app/checkpoints/mt3/', 'mt3')
274
+
275
+
276
+ def inference(audio):
277
+ with open(audio, 'rb') as fd:
278
+ contents = fd.read()
279
+ audio = upload_audio(contents,sample_rate=16000)
280
+
281
+ est_ns = inference_model(audio)
282
+
283
+ note_seq.sequence_proto_to_midi_file(est_ns, './transcribed.mid')
284
+
285
+ return './transcribed.mid'
286
+
287
+ title = "MT3"
288
+ description = "Gradio demo for MT3: Multi-Task Multitrack Music Transcription. To use it, simply upload your audio file, or click one of the examples to load them. Read more at the links below."
289
+
290
+ article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2111.03017' target='_blank'>MT3: Multi-Task Multitrack Music Transcription</a> | <a href='https://github.com/magenta/mt3' target='_blank'>Github Repo</a></p>"
291
+
292
+ examples=[['download.wav']]
293
+
294
+ gr.Interface(
295
+ inference,
296
+ gr.inputs.Audio(type="filepath", label="Input"),
297
+ [gr.outputs.File(label="Output")],
298
+ title=title,
299
+ description=description,
300
+ article=article,
301
+ examples=examples,
302
+ allow_flagging=False,
303
+ allow_screenshot=False,
304
+ enable_queue=True
305
+ ).launch()
download.wav ADDED
Binary file (320 kB). View file
 
packages.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+
2
+ build-essential
3
+ libasound2-dev
4
+ libjack-dev
requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ nest-asyncio
2
+ pyfluidsynth
3
+ absl-py
4
+ ddsp
5
+ flax
6
+ gin-config
7
+ immutabledict
8
+ librosa
9
+ mir_eval
10
+ note_seq
11
+ numpy
12
+ pretty_midi
13
+ scikit-learn
14
+ scipy
15
+ seqio
16
+ t5
17
+ tensorflow_cpu
18
+ tensorflow-datasets
19
+