Ahsen Khaliq commited on
Commit
f4e8264
1 Parent(s): 47cf8fb

Update app.py

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