mdnestor commited on
Commit
cc11df0
1 Parent(s): 065c57d

Create new file

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