oniati commited on
Commit
64f3e80
1 Parent(s): 8ea66cf

Create new file

Browse files
Files changed (1) hide show
  1. app.py +304 -0
app.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.system("pip install gradio==2.4.6")
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/inotiawu/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
+ import tensorflow.compat.v2 as tf
39
+
40
+ import functools
41
+ import gin
42
+ import jax
43
+ import librosa
44
+ import note_seq
45
+
46
+
47
+
48
+ import seqio
49
+ import t5
50
+ import t5x
51
+
52
+ from mt3 import metrics_utils
53
+ from mt3 import models
54
+ from mt3 import network
55
+ from mt3 import note_sequences
56
+ from mt3 import preprocessors
57
+ from mt3 import spectrograms
58
+ from mt3 import vocabularies
59
+
60
+
61
+ import nest_asyncio
62
+ nest_asyncio.apply()
63
+
64
+ SAMPLE_RATE = 16000
65
+ SF2_PATH = 'SGM-v2.01-Sal-Guit-Bass-V1.3.sf2'
66
+
67
+ def upload_audio(audio, sample_rate):
68
+ return note_seq.audio_io.wav_data_to_samples_librosa(
69
+ audio, sample_rate=sample_rate)
70
+
71
+
72
+
73
+ class InferenceModel(object):
74
+ """Wrapper of T5X model for music transcription."""
75
+
76
+ def __init__(self, checkpoint_path, model_type='mt3'):
77
+
78
+ # Model Constants.
79
+ if model_type == 'ismir2021':
80
+ num_velocity_bins = 127
81
+ self.encoding_spec = note_sequences.NoteEncodingSpec
82
+ self.inputs_length = 512
83
+ elif model_type == 'mt3':
84
+ num_velocity_bins = 1
85
+ self.encoding_spec = note_sequences.NoteEncodingWithTiesSpec
86
+ self.inputs_length = 256
87
+ else:
88
+ raise ValueError('unknown model_type: %s' % model_type)
89
+
90
+ gin_files = ['/home/user/app/mt3/gin/model.gin',
91
+ '/home/user/app/mt3/gin/mt3.gin']
92
+
93
+ self.batch_size = 8
94
+ self.outputs_length = 1024
95
+ self.sequence_length = {'inputs': self.inputs_length,
96
+ 'targets': self.outputs_length}
97
+
98
+ self.partitioner = t5x.partitioning.PjitPartitioner(
99
+ model_parallel_submesh=(1, 1, 1, 1), num_partitions=1)
100
+
101
+ # Build Codecs and Vocabularies.
102
+ self.spectrogram_config = spectrograms.SpectrogramConfig()
103
+ self.codec = vocabularies.build_codec(
104
+ vocab_config=vocabularies.VocabularyConfig(
105
+ num_velocity_bins=num_velocity_bins))
106
+ self.vocabulary = vocabularies.vocabulary_from_codec(self.codec)
107
+ self.output_features = {
108
+ 'inputs': seqio.ContinuousFeature(dtype=tf.float32, rank=2),
109
+ 'targets': seqio.Feature(vocabulary=self.vocabulary),
110
+ }
111
+
112
+ # Create a T5X model.
113
+ self._parse_gin(gin_files)
114
+ self.model = self._load_model()
115
+
116
+ # Restore from checkpoint.
117
+ self.restore_from_checkpoint(checkpoint_path)
118
+
119
+ @property
120
+ def input_shapes(self):
121
+ return {
122
+ 'encoder_input_tokens': (self.batch_size, self.inputs_length),
123
+ 'decoder_input_tokens': (self.batch_size, self.outputs_length)
124
+ }
125
+
126
+ def _parse_gin(self, gin_files):
127
+ """Parse gin files used to train the model."""
128
+ gin_bindings = [
129
+ 'from __gin__ import dynamic_registration',
130
+ 'from mt3 import vocabularies',
131
+ 'VOCAB_CONFIG=@vocabularies.VocabularyConfig()',
132
+ 'vocabularies.VocabularyConfig.num_velocity_bins=%NUM_VELOCITY_BINS'
133
+ ]
134
+ with gin.unlock_config():
135
+ gin.parse_config_files_and_bindings(
136
+ gin_files, gin_bindings, finalize_config=False)
137
+
138
+ def _load_model(self):
139
+ """Load up a T5X `Model` after parsing training gin config."""
140
+ model_config = gin.get_configurable(network.T5Config)()
141
+ module = network.Transformer(config=model_config)
142
+ return models.ContinuousInputsEncoderDecoderModel(
143
+ module=module,
144
+ input_vocabulary=self.output_features['inputs'].vocabulary,
145
+ output_vocabulary=self.output_features['targets'].vocabulary,
146
+ optimizer_def=t5x.adafactor.Adafactor(decay_rate=0.8, step_offset=0),
147
+ input_depth=spectrograms.input_depth(self.spectrogram_config))
148
+
149
+
150
+ def restore_from_checkpoint(self, checkpoint_path):
151
+ """Restore training state from checkpoint, resets self._predict_fn()."""
152
+ train_state_initializer = t5x.utils.TrainStateInitializer(
153
+ optimizer_def=self.model.optimizer_def,
154
+ init_fn=self.model.get_initial_variables,
155
+ input_shapes=self.input_shapes,
156
+ partitioner=self.partitioner)
157
+
158
+ restore_checkpoint_cfg = t5x.utils.RestoreCheckpointConfig(
159
+ path=checkpoint_path, mode='specific', dtype='float32')
160
+
161
+ train_state_axes = train_state_initializer.train_state_axes
162
+ self._predict_fn = self._get_predict_fn(train_state_axes)
163
+ self._train_state = train_state_initializer.from_checkpoint_or_scratch(
164
+ [restore_checkpoint_cfg], init_rng=jax.random.PRNGKey(0))
165
+
166
+ @functools.lru_cache()
167
+ def _get_predict_fn(self, train_state_axes):
168
+ """Generate a partitioned prediction function for decoding."""
169
+ def partial_predict_fn(params, batch, decode_rng):
170
+ return self.model.predict_batch_with_aux(
171
+ params, batch, decoder_params={'decode_rng': None})
172
+ return self.partitioner.partition(
173
+ partial_predict_fn,
174
+ in_axis_resources=(
175
+ train_state_axes.params,
176
+ t5x.partitioning.PartitionSpec('data',), None),
177
+ out_axis_resources=t5x.partitioning.PartitionSpec('data',)
178
+ )
179
+
180
+ def predict_tokens(self, batch, seed=0):
181
+ """Predict tokens from preprocessed dataset batch."""
182
+ prediction, _ = self._predict_fn(
183
+ self._train_state.params, batch, jax.random.PRNGKey(seed))
184
+ return self.vocabulary.decode_tf(prediction).numpy()
185
+
186
+ def __call__(self, audio):
187
+ """Infer note sequence from audio samples.
188
+
189
+ Args:
190
+ audio: 1-d numpy array of audio samples (16kHz) for a single example.
191
+ Returns:
192
+ A note_sequence of the transcribed audio.
193
+ """
194
+ ds = self.audio_to_dataset(audio)
195
+ ds = self.preprocess(ds)
196
+
197
+ model_ds = self.model.FEATURE_CONVERTER_CLS(pack=False)(
198
+ ds, task_feature_lengths=self.sequence_length)
199
+ model_ds = model_ds.batch(self.batch_size)
200
+
201
+ inferences = (tokens for batch in model_ds.as_numpy_iterator()
202
+ for tokens in self.predict_tokens(batch))
203
+
204
+ predictions = []
205
+ for example, tokens in zip(ds.as_numpy_iterator(), inferences):
206
+ predictions.append(self.postprocess(tokens, example))
207
+
208
+ result = metrics_utils.event_predictions_to_ns(
209
+ predictions, codec=self.codec, encoding_spec=self.encoding_spec)
210
+ return result['est_ns']
211
+
212
+ def audio_to_dataset(self, audio):
213
+ """Create a TF Dataset of spectrograms from input audio."""
214
+ frames, frame_times = self._audio_to_frames(audio)
215
+ return tf.data.Dataset.from_tensors({
216
+ 'inputs': frames,
217
+ 'input_times': frame_times,
218
+ })
219
+
220
+ def _audio_to_frames(self, audio):
221
+ """Compute spectrogram frames from audio."""
222
+ frame_size = self.spectrogram_config.hop_width
223
+ padding = [0, frame_size - len(audio) % frame_size]
224
+ audio = np.pad(audio, padding, mode='constant')
225
+ frames = spectrograms.split_audio(audio, self.spectrogram_config)
226
+ num_frames = len(audio) // frame_size
227
+ times = np.arange(num_frames) / self.spectrogram_config.frames_per_second
228
+ return frames, times
229
+
230
+ def preprocess(self, ds):
231
+ pp_chain = [
232
+ functools.partial(
233
+ t5.data.preprocessors.split_tokens_to_inputs_length,
234
+ sequence_length=self.sequence_length,
235
+ output_features=self.output_features,
236
+ feature_key='inputs',
237
+ additional_feature_keys=['input_times']),
238
+ # Cache occurs here during training.
239
+ preprocessors.add_dummy_targets,
240
+ functools.partial(
241
+ preprocessors.compute_spectrograms,
242
+ spectrogram_config=self.spectrogram_config)
243
+ ]
244
+ for pp in pp_chain:
245
+ ds = pp(ds)
246
+ return ds
247
+
248
+ def postprocess(self, tokens, example):
249
+ tokens = self._trim_eos(tokens)
250
+ start_time = example['input_times'][0]
251
+ # Round down to nearest symbolic token step.
252
+ start_time -= start_time % (1 / self.codec.steps_per_second)
253
+ return {
254
+ 'est_tokens': tokens,
255
+ 'start_time': start_time,
256
+ # Internal MT3 code expects raw inputs, not used here.
257
+ 'raw_inputs': []
258
+ }
259
+
260
+ @staticmethod
261
+ def _trim_eos(tokens):
262
+ tokens = np.array(tokens, np.int32)
263
+ if vocabularies.DECODED_EOS_ID in tokens:
264
+ tokens = tokens[:np.argmax(tokens == vocabularies.DECODED_EOS_ID)]
265
+ return tokens
266
+
267
+
268
+
269
+
270
+
271
+
272
+ inference_model = InferenceModel('/home/user/app/checkpoints/mt3/', 'mt3')
273
+
274
+
275
+ def inference(audio):
276
+ with open(audio, 'rb') as fd:
277
+ contents = fd.read()
278
+ audio = upload_audio(contents,sample_rate=16000)
279
+
280
+ est_ns = inference_model(audio)
281
+
282
+ note_seq.sequence_proto_to_midi_file(est_ns, './transcribed.mid')
283
+
284
+ return './transcribed.mid'
285
+
286
+ title = "MT3"
287
+ 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."
288
+
289
+ 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>"
290
+
291
+ examples=[['download.wav']]
292
+
293
+ gr.Interface(
294
+ inference,
295
+ gr.inputs.Audio(type="filepath", label="Input"),
296
+ [gr.outputs.File(label="Output")],
297
+ title=title,
298
+ description=description,
299
+ article=article,
300
+ examples=examples,
301
+ allow_flagging=False,
302
+ allow_screenshot=False,
303
+ enable_queue=True
304
+ ).launch()