EdanMizrahi commited on
Commit
e7358e0
1 Parent(s): 5406929

Create app.py

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