yeyi9 commited on
Commit
4640a6c
1 Parent(s): 01464af

Upload 4 files

Browse files
Files changed (4) hide show
  1. Dockerfile +2 -0
  2. app.py +295 -0
  3. packages.txt +4 -0
  4. requirements.txt +18 -0
Dockerfile ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ RUN echo "deb http://deb.debian.org/debian buster main" >> /etc/apt/sources.list && \
2
+ apt-get update
app.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.system("pip install gradio==2.4.6")
3
+ import gradio as gr
4
+ from pathlib import Path
5
+ os.system("pip install gsutil")
6
+
7
+
8
+ os.system("git clone --branch=main https://github.com/google-research/t5x")
9
+ os.system("mv t5x t5x_tmp; mv t5x_tmp/* .; rm -r t5x_tmp")
10
+ os.system("sed -i 's:jax\[tpu\]:jax:' setup.py")
11
+ os.system("python3 -m pip install -e .")
12
+
13
+
14
+ # install mt3
15
+ os.system("git clone --branch=main https://github.com/magenta/mt3")
16
+ os.system("mv mt3 mt3_tmp; mv mt3_tmp/* .; rm -r mt3_tmp")
17
+ os.system("python3 -m pip install -e .")
18
+
19
+ # copy checkpoints
20
+ os.system("gsutil -q -m cp -r gs://mt3/checkpoints .")
21
+
22
+ # copy soundfont (originally from https://sites.google.com/site/soundfonts4u)
23
+ os.system("gsutil -q -m cp gs://magentadata/soundfonts/SGM-v2.01-Sal-Guit-Bass-V1.3.sf2 .")
24
+
25
+ #@title Imports and Definitions
26
+
27
+ import functools
28
+ import os
29
+
30
+ import numpy as np
31
+ import tensorflow.compat.v2 as tf
32
+
33
+ import functools
34
+ import gin
35
+ import jax
36
+ import librosa
37
+ import note_seq
38
+ import seqio
39
+ import t5
40
+ import t5x
41
+
42
+ from mt3 import metrics_utils
43
+ from mt3 import models
44
+ from mt3 import network
45
+ from mt3 import note_sequences
46
+ from mt3 import preprocessors
47
+ from mt3 import spectrograms
48
+ from mt3 import vocabularies
49
+
50
+
51
+ import nest_asyncio
52
+ nest_asyncio.apply()
53
+
54
+ SAMPLE_RATE = 16000
55
+ SF2_PATH = 'SGM-v2.01-Sal-Guit-Bass-V1.3.sf2'
56
+
57
+ def upload_audio(audio, sample_rate):
58
+ return note_seq.audio_io.wav_data_to_samples_librosa(
59
+ audio, sample_rate=sample_rate)
60
+
61
+
62
+
63
+ class InferenceModel(object):
64
+ """Wrapper of T5X model for music transcription."""
65
+
66
+ def __init__(self, checkpoint_path, model_type='mt3'):
67
+
68
+ # Model Constants.
69
+ if model_type == 'ismir2021':
70
+ num_velocity_bins = 127
71
+ self.encoding_spec = note_sequences.NoteEncodingSpec
72
+ self.inputs_length = 512
73
+ elif model_type == 'mt3':
74
+ num_velocity_bins = 1
75
+ self.encoding_spec = note_sequences.NoteEncodingWithTiesSpec
76
+ self.inputs_length = 256
77
+ else:
78
+ raise ValueError('unknown model_type: %s' % model_type)
79
+
80
+ gin_files = ['/home/user/app/mt3/gin/model.gin',
81
+ '/home/user/app/mt3/gin/mt3.gin']
82
+
83
+ self.batch_size = 8
84
+ self.outputs_length = 1024
85
+ self.sequence_length = {'inputs': self.inputs_length,
86
+ 'targets': self.outputs_length}
87
+
88
+ self.partitioner = t5x.partitioning.ModelBasedPjitPartitioner(
89
+ model_parallel_submesh=(1, 1, 1, 1), num_partitions=1)
90
+
91
+ # Build Codecs and Vocabularies.
92
+ self.spectrogram_config = spectrograms.SpectrogramConfig()
93
+ self.codec = vocabularies.build_codec(
94
+ vocab_config=vocabularies.VocabularyConfig(
95
+ num_velocity_bins=num_velocity_bins))
96
+ self.vocabulary = vocabularies.vocabulary_from_codec(self.codec)
97
+ self.output_features = {
98
+ 'inputs': seqio.ContinuousFeature(dtype=tf.float32, rank=2),
99
+ 'targets': seqio.Feature(vocabulary=self.vocabulary),
100
+ }
101
+
102
+ # Create a T5X model.
103
+ self._parse_gin(gin_files)
104
+ self.model = self._load_model()
105
+
106
+ # Restore from checkpoint.
107
+ self.restore_from_checkpoint(checkpoint_path)
108
+
109
+ @property
110
+ def input_shapes(self):
111
+ return {
112
+ 'encoder_input_tokens': (self.batch_size, self.inputs_length),
113
+ 'decoder_input_tokens': (self.batch_size, self.outputs_length)
114
+ }
115
+
116
+ def _parse_gin(self, gin_files):
117
+ """Parse gin files used to train the model."""
118
+ gin_bindings = [
119
+ 'from __gin__ import dynamic_registration',
120
+ 'from mt3 import vocabularies',
121
+ 'VOCAB_CONFIG=@vocabularies.VocabularyConfig()',
122
+ 'vocabularies.VocabularyConfig.num_velocity_bins=%NUM_VELOCITY_BINS'
123
+ ]
124
+ with gin.unlock_config():
125
+ gin.parse_config_files_and_bindings(
126
+ gin_files, gin_bindings, finalize_config=False)
127
+
128
+ def _load_model(self):
129
+ """Load up a T5X `Model` after parsing training gin config."""
130
+ model_config = gin.get_configurable(network.T5Config)()
131
+ module = network.Transformer(config=model_config)
132
+ return models.ContinuousInputsEncoderDecoderModel(
133
+ module=module,
134
+ input_vocabulary=self.output_features['inputs'].vocabulary,
135
+ output_vocabulary=self.output_features['targets'].vocabulary,
136
+ optimizer_def=t5x.adafactor.Adafactor(decay_rate=0.8, step_offset=0),
137
+ input_depth=spectrograms.input_depth(self.spectrogram_config))
138
+
139
+
140
+ def restore_from_checkpoint(self, checkpoint_path):
141
+ """Restore training state from checkpoint, resets self._predict_fn()."""
142
+ train_state_initializer = t5x.utils.TrainStateInitializer(
143
+ optimizer_def=self.model.optimizer_def,
144
+ init_fn=self.model.get_initial_variables,
145
+ input_shapes=self.input_shapes,
146
+ partitioner=self.partitioner)
147
+
148
+ restore_checkpoint_cfg = t5x.utils.RestoreCheckpointConfig(
149
+ path=checkpoint_path, mode='specific', dtype='float32')
150
+
151
+ train_state_axes = train_state_initializer.train_state_axes
152
+ self._predict_fn = self._get_predict_fn(train_state_axes)
153
+ self._train_state = train_state_initializer.from_checkpoint_or_scratch(
154
+ [restore_checkpoint_cfg], init_rng=jax.random.PRNGKey(0))
155
+
156
+ @functools.lru_cache()
157
+ def _get_predict_fn(self, train_state_axes):
158
+ """Generate a partitioned prediction function for decoding."""
159
+ def partial_predict_fn(params, batch, decode_rng):
160
+ return self.model.predict_batch_with_aux(
161
+ params, batch, decoder_params={'decode_rng': None})
162
+ return self.partitioner.partition(
163
+ partial_predict_fn,
164
+ in_axis_resources=(
165
+ train_state_axes.params,
166
+ t5x.partitioning.PartitionSpec('data',), None),
167
+ out_axis_resources=t5x.partitioning.PartitionSpec('data',)
168
+ )
169
+
170
+ def predict_tokens(self, batch, seed=0):
171
+ """Predict tokens from preprocessed dataset batch."""
172
+ prediction, _ = self._predict_fn(
173
+ self._train_state.params, batch, jax.random.PRNGKey(seed))
174
+ return self.vocabulary.decode_tf(prediction).numpy()
175
+
176
+ def __call__(self, audio):
177
+ """Infer note sequence from audio samples.
178
+
179
+ Args:
180
+ audio: 1-d numpy array of audio samples (16kHz) for a single example.
181
+
182
+ Returns:
183
+ A note_sequence of the transcribed audio.
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
+ """Create a TF Dataset of spectrograms from input audio."""
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
+ """Compute spectrogram frames from audio."""
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
+ # Cache occurs here during training.
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
+ # Round down to nearest symbolic token step.
243
+ start_time -= start_time % (1 / self.codec.steps_per_second)
244
+ return {
245
+ 'est_tokens': tokens,
246
+ 'start_time': start_time,
247
+ # Internal MT3 code expects raw inputs, not used here.
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
+
259
+
260
+
261
+
262
+
263
+ inference_model = InferenceModel('/home/user/app/checkpoints/mt3/', 'mt3')
264
+
265
+
266
+ def inference(audio):
267
+ with open(audio, 'rb') as fd:
268
+ contents = fd.read()
269
+ audio = upload_audio(contents,sample_rate=16000)
270
+
271
+ est_ns = inference_model(audio)
272
+
273
+ note_seq.sequence_proto_to_midi_file(est_ns, './transcribed.mid')
274
+
275
+ return './transcribed.mid'
276
+
277
+ title = "MT3"
278
+ 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."
279
+
280
+ 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>"
281
+
282
+ examples=[['download.wav']]
283
+
284
+ gr.Interface(
285
+ inference,
286
+ gr.inputs.Audio(type="filepath", label="Input"),
287
+ [gr.outputs.File(label="Output")],
288
+ title=title,
289
+ description=description,
290
+ article=article,
291
+ examples=examples,
292
+ allow_flagging=False,
293
+ allow_screenshot=False,
294
+ enable_queue=True
295
+ ).launch()
packages.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ libfluidsynth1
2
+ build-essential
3
+ libasound2-dev
4
+ libjack-dev
requirements.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
18
+ tensorflow-datasets