hero-intelligent commited on
Commit
bfbddd2
·
1 Parent(s): 7d193a7

Upload 8 files

Browse files
.gitattributes CHANGED
@@ -2,13 +2,11 @@
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
  *.model filter=lfs diff=lfs merge=lfs -text
13
  *.msgpack filter=lfs diff=lfs merge=lfs -text
14
  *.npy filter=lfs diff=lfs merge=lfs -text
@@ -16,13 +14,12 @@
16
  *.onnx filter=lfs diff=lfs merge=lfs -text
17
  *.ot filter=lfs diff=lfs merge=lfs -text
18
  *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
  *.pickle filter=lfs diff=lfs merge=lfs -text
21
  *.pkl filter=lfs diff=lfs merge=lfs -text
 
22
  *.pt filter=lfs diff=lfs merge=lfs -text
23
  *.pth filter=lfs diff=lfs merge=lfs -text
24
  *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
28
  *.tflite filter=lfs diff=lfs merge=lfs -text
@@ -30,5 +27,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
  *.wasm filter=lfs diff=lfs merge=lfs -text
31
  *.xz filter=lfs diff=lfs merge=lfs -text
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
- *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
 
5
  *.ftz filter=lfs diff=lfs merge=lfs -text
6
  *.gz filter=lfs diff=lfs merge=lfs -text
7
  *.h5 filter=lfs diff=lfs merge=lfs -text
8
  *.joblib filter=lfs diff=lfs merge=lfs -text
9
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
 
10
  *.model filter=lfs diff=lfs merge=lfs -text
11
  *.msgpack filter=lfs diff=lfs merge=lfs -text
12
  *.npy filter=lfs diff=lfs merge=lfs -text
 
14
  *.onnx filter=lfs diff=lfs merge=lfs -text
15
  *.ot filter=lfs diff=lfs merge=lfs -text
16
  *.parquet filter=lfs diff=lfs merge=lfs -text
 
17
  *.pickle filter=lfs diff=lfs merge=lfs -text
18
  *.pkl filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
  *.pt filter=lfs diff=lfs merge=lfs -text
21
  *.pth filter=lfs diff=lfs merge=lfs -text
22
  *.rar filter=lfs diff=lfs merge=lfs -text
 
23
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
  *.tar.* filter=lfs diff=lfs merge=lfs -text
25
  *.tflite filter=lfs diff=lfs merge=lfs -text
 
27
  *.wasm filter=lfs diff=lfs merge=lfs -text
28
  *.xz filter=lfs diff=lfs merge=lfs -text
29
  *.zip filter=lfs diff=lfs merge=lfs -text
30
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
31
  *tfevents* filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM tensorflow/tensorflow:latest-gpu
2
+
3
+ WORKDIR /home/user/app
4
+
5
+ # prepare environments
6
+ RUN apt update && apt install -y git libfluidsynth2 build-essential libasound2-dev libjack-dev
7
+ RUN pip install gradio gsutil
8
+ RUN git clone --branch=main https://github.com/google-research/t5x; \
9
+ mv t5x t5x_tmp; mv t5x_tmp/* .; rm -r t5x_tmp
10
+ RUN sed -i 's:jax\[tpu\]:jax:' setup.py
11
+ RUN python3 -m pip install -e .
12
+ RUN python3 -m pip install --upgrade pip
13
+
14
+ # install mt3
15
+ RUN git clone --branch=main https://github.com/magenta/mt3; \
16
+ mv mt3 mt3_tmp; mv mt3_tmp/* .; rm -r mt3_tmp
17
+ RUN python3 -m pip install -e .
18
+ # RUN pip install tensorflow_cpu
19
+
20
+ # copy checkpoints
21
+ RUN gsutil -q -m cp -r gs://mt3/checkpoints .
22
+
23
+ # copy soundfont (originally from https://sites.google.com/site/soundfonts4u)
24
+ RUN gsutil -q -m cp gs://magentadata/soundfonts/SGM-v2.01-Sal-Guit-Bass-V1.3.sf2 .
25
+
26
+ RUN pip install ffmpeg
27
+ RUN apt install -y ffmpeg
28
+ COPY ./requirements.txt ./requirements.txt
29
+ RUN pip install -r requirements.txt
30
+ COPY . .
31
+
32
+ EXPOSE 7860
33
+
34
+ CMD [ "python", "app.py" ]
app.old.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.system("pip install gradio")
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/google-research/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
+
39
+ import tensorflow.compat.v2 as tf
40
+
41
+ import functools
42
+ import gin
43
+ import jax
44
+ import librosa
45
+ import note_seq
46
+
47
+
48
+
49
+ import seqio
50
+ import t5
51
+ import t5x
52
+
53
+ from mt3 import metrics_utils
54
+ from mt3 import models
55
+ from mt3 import network
56
+ from mt3 import note_sequences
57
+ from mt3 import preprocessors
58
+ from mt3 import spectrograms
59
+ from mt3 import vocabularies
60
+
61
+
62
+ import nest_asyncio
63
+ nest_asyncio.apply()
64
+
65
+ SAMPLE_RATE = 16000
66
+ SF2_PATH = 'SGM-v2.01-Sal-Guit-Bass-V1.3.sf2'
67
+
68
+ def upload_audio(audio, sample_rate):
69
+ return note_seq.audio_io.wav_data_to_samples_librosa(
70
+ audio, sample_rate=sample_rate)
71
+
72
+
73
+
74
+ class InferenceModel(object):
75
+ """Wrapper of T5X model for music transcription."""
76
+
77
+ def __init__(self, checkpoint_path, model_type='mt3'):
78
+
79
+ # Model Constants.
80
+ if model_type == 'ismir2021':
81
+ num_velocity_bins = 127
82
+ self.encoding_spec = note_sequences.NoteEncodingSpec
83
+ self.inputs_length = 512
84
+ elif model_type == 'mt3':
85
+ num_velocity_bins = 1
86
+ self.encoding_spec = note_sequences.NoteEncodingWithTiesSpec
87
+ self.inputs_length = 256
88
+ else:
89
+ raise ValueError('unknown model_type: %s' % model_type)
90
+
91
+ gin_files = ['/home/user/app/mt3/gin/model.gin',
92
+ '/home/user/app/mt3/gin/mt3.gin']
93
+
94
+ self.batch_size = 8
95
+ self.outputs_length = 1024
96
+ self.sequence_length = {'inputs': self.inputs_length,
97
+ 'targets': self.outputs_length}
98
+
99
+ self.partitioner = t5x.partitioning.PjitPartitioner(
100
+ model_parallel_submesh=None, num_partitions=1)
101
+
102
+ # Build Codecs and Vocabularies.
103
+ self.spectrogram_config = spectrograms.SpectrogramConfig()
104
+ self.codec = vocabularies.build_codec(
105
+ vocab_config=vocabularies.VocabularyConfig(
106
+ num_velocity_bins=num_velocity_bins))
107
+ self.vocabulary = vocabularies.vocabulary_from_codec(self.codec)
108
+ self.output_features = {
109
+ 'inputs': seqio.ContinuousFeature(dtype=tf.float32, rank=2),
110
+ 'targets': seqio.Feature(vocabulary=self.vocabulary),
111
+ }
112
+
113
+ # Create a T5X model.
114
+ self._parse_gin(gin_files)
115
+ self.model = self._load_model()
116
+
117
+ # Restore from checkpoint.
118
+ self.restore_from_checkpoint(checkpoint_path)
119
+
120
+ @property
121
+ def input_shapes(self):
122
+ return {
123
+ 'encoder_input_tokens': (self.batch_size, self.inputs_length),
124
+ 'decoder_input_tokens': (self.batch_size, self.outputs_length)
125
+ }
126
+
127
+ def _parse_gin(self, gin_files):
128
+ """Parse gin files used to train the model."""
129
+ gin_bindings = [
130
+ 'from __gin__ import dynamic_registration',
131
+ 'from mt3 import vocabularies',
132
133
+ 'vocabularies.VocabularyConfig.num_velocity_bins=%NUM_VELOCITY_BINS'
134
+ ]
135
+ with gin.unlock_config():
136
+ gin.parse_config_files_and_bindings(
137
+ gin_files, gin_bindings, finalize_config=False)
138
+
139
+ def _load_model(self):
140
+ """Load up a T5X `Model` after parsing training gin config."""
141
+ model_config = gin.get_configurable(network.T5Config)()
142
+ module = network.Transformer(config=model_config)
143
+ return models.ContinuousInputsEncoderDecoderModel(
144
+ module=module,
145
+ input_vocabulary=self.output_features['inputs'].vocabulary,
146
+ output_vocabulary=self.output_features['targets'].vocabulary,
147
+ optimizer_def=t5x.adafactor.Adafactor(decay_rate=0.8, step_offset=0),
148
+ input_depth=spectrograms.input_depth(self.spectrogram_config))
149
+
150
+
151
+ def restore_from_checkpoint(self, checkpoint_path):
152
+ """Restore training state from checkpoint, resets self._predict_fn()."""
153
+ train_state_initializer = t5x.utils.TrainStateInitializer(
154
+ optimizer_def=self.model.optimizer_def,
155
+ init_fn=self.model.get_initial_variables,
156
+ input_shapes=self.input_shapes,
157
+ partitioner=self.partitioner)
158
+
159
+ restore_checkpoint_cfg = t5x.utils.RestoreCheckpointConfig(
160
+ path=checkpoint_path, mode='specific', dtype='float32')
161
+
162
+ train_state_axes = train_state_initializer.train_state_axes
163
+ self._predict_fn = self._get_predict_fn(train_state_axes)
164
+ self._train_state = train_state_initializer.from_checkpoint_or_scratch(
165
+ [restore_checkpoint_cfg], init_rng=jax.random.PRNGKey(0))
166
+
167
+ @functools.lru_cache()
168
+ def _get_predict_fn(self, train_state_axes):
169
+ """Generate a partitioned prediction function for decoding."""
170
+ def partial_predict_fn(params, batch, decode_rng):
171
+ return self.model.predict_batch_with_aux(
172
+ params, batch, decoder_params={'decode_rng': None})
173
+ return self.partitioner.partition(
174
+ partial_predict_fn,
175
+ in_axis_resources=(
176
+ train_state_axes.params,
177
+ t5x.partitioning.PartitionSpec('data',), None),
178
+ out_axis_resources=t5x.partitioning.PartitionSpec('data',)
179
+ )
180
+
181
+ def predict_tokens(self, batch, seed=0):
182
+ """Predict tokens from preprocessed dataset batch."""
183
+ prediction, _ = self._predict_fn(
184
+ self._train_state.params, batch, jax.random.PRNGKey(seed))
185
+ return self.vocabulary.decode_tf(prediction).numpy()
186
+
187
+ def __call__(self, audio):
188
+ """Infer note sequence from audio samples.
189
+
190
+ Args:
191
+ audio: 1-d numpy array of audio samples (16kHz) for a single example.
192
+ Returns:
193
+ A note_sequence of the transcribed audio.
194
+ """
195
+ ds = self.audio_to_dataset(audio)
196
+ ds = self.preprocess(ds)
197
+
198
+ model_ds = self.model.FEATURE_CONVERTER_CLS(pack=False)(
199
+ ds, task_feature_lengths=self.sequence_length)
200
+ model_ds = model_ds.batch(self.batch_size)
201
+
202
+ inferences = (tokens for batch in model_ds.as_numpy_iterator()
203
+ for tokens in self.predict_tokens(batch))
204
+
205
+ predictions = []
206
+ for example, tokens in zip(ds.as_numpy_iterator(), inferences):
207
+ predictions.append(self.postprocess(tokens, example))
208
+
209
+ result = metrics_utils.event_predictions_to_ns(
210
+ predictions, codec=self.codec, encoding_spec=self.encoding_spec)
211
+ return result['est_ns']
212
+
213
+ def audio_to_dataset(self, audio):
214
+ """Create a TF Dataset of spectrograms from input audio."""
215
+ frames, frame_times = self._audio_to_frames(audio)
216
+ return tf.data.Dataset.from_tensors({
217
+ 'inputs': frames,
218
+ 'input_times': frame_times,
219
+ })
220
+
221
+ def _audio_to_frames(self, audio):
222
+ """Compute spectrogram frames from audio."""
223
+ frame_size = self.spectrogram_config.hop_width
224
+ padding = [0, frame_size - len(audio) % frame_size]
225
+ audio = np.pad(audio, padding, mode='constant')
226
+ frames = spectrograms.split_audio(audio, self.spectrogram_config)
227
+ num_frames = len(audio) // frame_size
228
+ times = np.arange(num_frames) / self.spectrogram_config.frames_per_second
229
+ return frames, times
230
+
231
+ def preprocess(self, ds):
232
+ pp_chain = [
233
+ functools.partial(
234
+ t5.data.preprocessors.split_tokens_to_inputs_length,
235
+ sequence_length=self.sequence_length,
236
+ output_features=self.output_features,
237
+ feature_key='inputs',
238
+ additional_feature_keys=['input_times']),
239
+ # Cache occurs here during training.
240
+ preprocessors.add_dummy_targets,
241
+ functools.partial(
242
+ preprocessors.compute_spectrograms,
243
+ spectrogram_config=self.spectrogram_config)
244
+ ]
245
+ for pp in pp_chain:
246
+ ds = pp(ds)
247
+ return ds
248
+
249
+ def postprocess(self, tokens, example):
250
+ tokens = self._trim_eos(tokens)
251
+ start_time = example['input_times'][0]
252
+ # Round down to nearest symbolic token step.
253
+ start_time -= start_time % (1 / self.codec.steps_per_second)
254
+ return {
255
+ 'est_tokens': tokens,
256
+ 'start_time': start_time,
257
+ # Internal MT3 code expects raw inputs, not used here.
258
+ 'raw_inputs': []
259
+ }
260
+
261
+ @staticmethod
262
+ def _trim_eos(tokens):
263
+ tokens = np.array(tokens, np.int32)
264
+ if vocabularies.DECODED_EOS_ID in tokens:
265
+ tokens = tokens[:np.argmax(tokens == vocabularies.DECODED_EOS_ID)]
266
+ return tokens
267
+
268
+
269
+
270
+
271
+
272
+
273
+ inference_model = InferenceModel('/home/user/app/checkpoints/mt3/', 'mt3')
274
+
275
+
276
+ def inference(audio):
277
+ with open(audio, 'rb') as fd:
278
+ contents = fd.read()
279
+ audio = upload_audio(contents,sample_rate=16000)
280
+
281
+ est_ns = inference_model(audio)
282
+
283
+ note_seq.sequence_proto_to_midi_file(est_ns, './transcribed.mid')
284
+
285
+ return './transcribed.mid'
286
+
287
+ title = "MT3"
288
+ 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."
289
+
290
+ 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>"
291
+
292
+ examples=[['download.wav']]
293
+
294
+ gr.Interface(
295
+ inference,
296
+ gr.inputs.Audio(type="filepath", label="Input"),
297
+ [gr.outputs.File(label="Output")],
298
+ title=title,
299
+ description=description,
300
+ article=article,
301
+ examples=examples,
302
+ allow_flagging=False,
303
+ allow_screenshot=False,
304
+ enable_queue=True
305
+ ).launch()
app.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+
4
+ from imports_and_definitions import InferenceModel
5
+ from imports_and_definitions import upload_audio
6
+ import note_seq
7
+
8
+ def inference(audio,model):
9
+ with open(audio, 'rb') as fd:
10
+ contents = fd.read()
11
+ audio = upload_audio(contents,sample_rate=16000)
12
+ inference_model = InferenceModel('/home/user/app/checkpoints/' + str(model) + '/', str(model))
13
+ est_ns = inference_model(audio)
14
+ note_seq.sequence_proto_to_midi_file(est_ns, './transcribed.mid')
15
+ return './transcribed.mid'
16
+
17
+ title = "MT3"
18
+ description = """
19
+ Gradio demo for MT3: Multi-Task Multitrack Music Transcription. To use it, simply upload your audio file, then choose either ismir2021 for piano transcription or mt3 for multi-instrument transcription. Read more at the links below.
20
+ It will be of better quality if pure music is inputted. It is recomended to remove the voice in a song first using UVR5. Check it out in the links below.
21
+ """
22
+
23
+ article = """
24
+ <p style='text-align: center'>
25
+ MT3:
26
+ <a href='https://arxiv.org/abs/2111.03017' target='_blank'>Multi-Task Multitrack Music Transcription</a> |
27
+ <a href='https://github.com/magenta/mt3' target='_blank'>Github Repo</a> |
28
+ <a href='https://huggingface.co/spaces/oniati/mrt/tree/main' target='_blank'>Huggingface</a> |
29
+ <a href='https://github.com/hero-intelligent/MT3-Docker' target='_blank'>Docker Source Code</a>
30
+ </p>
31
+ <p style='text-align: center'>
32
+ UVR5:
33
+ <a href='https://ultimatevocalremover.com/' target='_blank'>Official Site</a> |
34
+ <a href='https://github.com/Anjok07/ultimatevocalremovergui' target='_blank'>Github Repo</a>
35
+ </p>
36
+ """
37
+
38
+ demo = gr.Interface(
39
+ fn=inference,
40
+ inputs=[
41
+ gr.inputs.Audio(type="filepath", label="Input"),
42
+ gr.Dropdown(choices=["mt3", "ismir2021"], value="mt3")
43
+ ],
44
+ outputs=[gr.outputs.File(label="Output")],
45
+ title=title,
46
+ description=description,
47
+ article=article,
48
+ allow_flagging=False,
49
+ allow_screenshot=False,
50
+ enable_queue=True
51
+ )
52
+ demo.launch(server_name="0.0.0.0")
imports_and_definitions.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import os
3
+
4
+ import numpy as np
5
+
6
+ import tensorflow.compat.v2 as tf
7
+
8
+ import functools
9
+ import gin
10
+ import jax
11
+ import librosa
12
+ import note_seq
13
+
14
+
15
+
16
+ import seqio
17
+ import t5
18
+ import t5x
19
+
20
+ from mt3 import metrics_utils
21
+ from mt3 import models
22
+ from mt3 import network
23
+ from mt3 import note_sequences
24
+ from mt3 import preprocessors
25
+ from mt3 import spectrograms
26
+ from mt3 import vocabularies
27
+
28
+
29
+ import nest_asyncio
30
+ nest_asyncio.apply()
31
+
32
+ SAMPLE_RATE = 16000
33
+ SF2_PATH = 'SGM-v2.01-Sal-Guit-Bass-V1.3.sf2'
34
+
35
+ def upload_audio(audio, sample_rate):
36
+ return note_seq.audio_io.wav_data_to_samples_librosa(
37
+ audio, sample_rate=sample_rate)
38
+
39
+
40
+
41
+ class InferenceModel(object):
42
+ """Wrapper of T5X model for music transcription."""
43
+
44
+ def __init__(self, checkpoint_path, model_type='mt3'):
45
+
46
+ # Model Constants.
47
+
48
+ # two and only two elements needed in list gin_files.
49
+ gin_files = ['/home/user/app/mt3/gin/model.gin']
50
+
51
+ # append another element here in if block.
52
+ if model_type == 'mt3':
53
+ num_velocity_bins = 1
54
+ self.encoding_spec = note_sequences.NoteEncodingWithTiesSpec
55
+ self.inputs_length = 256
56
+ gin_files.append('/home/user/app/mt3/gin/mt3.gin')
57
+ elif model_type == 'ismir2021':
58
+ num_velocity_bins = 127
59
+ self.encoding_spec = note_sequences.NoteEncodingSpec
60
+ self.inputs_length = 512
61
+ gin_files.append('/home/user/app/mt3/gin/ismir2021.gin')
62
+ else:
63
+ raise ValueError('unknown model_type: %s' % model_type)
64
+ gin_files.append('/home/user/app/mt3/gin/mt3.gin')
65
+
66
+ self.batch_size = 8
67
+ self.outputs_length = 1024
68
+ self.sequence_length = {'inputs': self.inputs_length,
69
+ 'targets': self.outputs_length}
70
+
71
+ self.partitioner = t5x.partitioning.PjitPartitioner(
72
+ model_parallel_submesh=None, num_partitions=1)
73
+
74
+ # Build Codecs and Vocabularies.
75
+ self.spectrogram_config = spectrograms.SpectrogramConfig()
76
+ self.codec = vocabularies.build_codec(
77
+ vocab_config=vocabularies.VocabularyConfig(
78
+ num_velocity_bins=num_velocity_bins))
79
+ self.vocabulary = vocabularies.vocabulary_from_codec(self.codec)
80
+ self.output_features = {
81
+ 'inputs': seqio.ContinuousFeature(dtype=tf.float32, rank=2),
82
+ 'targets': seqio.Feature(vocabulary=self.vocabulary),
83
+ }
84
+
85
+ # Create a T5X model.
86
+ self._parse_gin(gin_files)
87
+ self.model = self._load_model()
88
+
89
+ # Restore from checkpoint.
90
+ self.restore_from_checkpoint(checkpoint_path)
91
+
92
+ @property
93
+ def input_shapes(self):
94
+ return {
95
+ 'encoder_input_tokens': (self.batch_size, self.inputs_length),
96
+ 'decoder_input_tokens': (self.batch_size, self.outputs_length)
97
+ }
98
+
99
+ def _parse_gin(self, gin_files):
100
+ """Parse gin files used to train the model."""
101
+ gin_bindings = [
102
+ 'from __gin__ import dynamic_registration',
103
+ 'from mt3 import vocabularies',
104
105
+ 'vocabularies.VocabularyConfig.num_velocity_bins=%NUM_VELOCITY_BINS'
106
+ ]
107
+ with gin.unlock_config():
108
+ gin.parse_config_files_and_bindings(
109
+ gin_files, gin_bindings, finalize_config=False)
110
+
111
+ def _load_model(self):
112
+ """Load up a T5X `Model` after parsing training gin config."""
113
+ model_config = gin.get_configurable(network.T5Config)()
114
+ module = network.Transformer(config=model_config)
115
+ return models.ContinuousInputsEncoderDecoderModel(
116
+ module=module,
117
+ input_vocabulary=self.output_features['inputs'].vocabulary,
118
+ output_vocabulary=self.output_features['targets'].vocabulary,
119
+ optimizer_def=t5x.adafactor.Adafactor(decay_rate=0.8, step_offset=0),
120
+ input_depth=spectrograms.input_depth(self.spectrogram_config))
121
+
122
+
123
+ def restore_from_checkpoint(self, checkpoint_path):
124
+ """Restore training state from checkpoint, resets self._predict_fn()."""
125
+ train_state_initializer = t5x.utils.TrainStateInitializer(
126
+ optimizer_def=self.model.optimizer_def,
127
+ init_fn=self.model.get_initial_variables,
128
+ input_shapes=self.input_shapes,
129
+ partitioner=self.partitioner)
130
+
131
+ restore_checkpoint_cfg = t5x.utils.RestoreCheckpointConfig(
132
+ path=checkpoint_path, mode='specific', dtype='float32')
133
+
134
+ train_state_axes = train_state_initializer.train_state_axes
135
+ self._predict_fn = self._get_predict_fn(train_state_axes)
136
+ self._train_state = train_state_initializer.from_checkpoint_or_scratch(
137
+ [restore_checkpoint_cfg], init_rng=jax.random.PRNGKey(0))
138
+
139
+ @functools.lru_cache()
140
+ def _get_predict_fn(self, train_state_axes):
141
+ """Generate a partitioned prediction function for decoding."""
142
+ def partial_predict_fn(params, batch, decode_rng):
143
+ return self.model.predict_batch_with_aux(
144
+ params, batch, decoder_params={'decode_rng': None})
145
+ return self.partitioner.partition(
146
+ partial_predict_fn,
147
+ in_axis_resources=(
148
+ train_state_axes.params,
149
+ t5x.partitioning.PartitionSpec('data',), None),
150
+ out_axis_resources=t5x.partitioning.PartitionSpec('data',)
151
+ )
152
+
153
+ def predict_tokens(self, batch, seed=0):
154
+ """Predict tokens from preprocessed dataset batch."""
155
+ prediction, _ = self._predict_fn(
156
+ self._train_state.params, batch, jax.random.PRNGKey(seed))
157
+ return self.vocabulary.decode_tf(prediction).numpy()
158
+
159
+ def __call__(self, audio):
160
+ """Infer note sequence from audio samples.
161
+
162
+ Args:
163
+ audio: 1-d numpy array of audio samples (16kHz) for a single example.
164
+ Returns:
165
+ A note_sequence of the transcribed audio.
166
+ """
167
+ ds = self.audio_to_dataset(audio)
168
+ ds = self.preprocess(ds)
169
+
170
+ model_ds = self.model.FEATURE_CONVERTER_CLS(pack=False)(
171
+ ds, task_feature_lengths=self.sequence_length)
172
+ model_ds = model_ds.batch(self.batch_size)
173
+
174
+ inferences = (tokens for batch in model_ds.as_numpy_iterator()
175
+ for tokens in self.predict_tokens(batch))
176
+
177
+ predictions = []
178
+ for example, tokens in zip(ds.as_numpy_iterator(), inferences):
179
+ predictions.append(self.postprocess(tokens, example))
180
+
181
+ result = metrics_utils.event_predictions_to_ns(
182
+ predictions, codec=self.codec, encoding_spec=self.encoding_spec)
183
+ return result['est_ns']
184
+
185
+ def audio_to_dataset(self, audio):
186
+ """Create a TF Dataset of spectrograms from input audio."""
187
+ frames, frame_times = self._audio_to_frames(audio)
188
+ return tf.data.Dataset.from_tensors({
189
+ 'inputs': frames,
190
+ 'input_times': frame_times,
191
+ })
192
+
193
+ def _audio_to_frames(self, audio):
194
+ """Compute spectrogram frames from audio."""
195
+ frame_size = self.spectrogram_config.hop_width
196
+ padding = [0, frame_size - len(audio) % frame_size]
197
+ audio = np.pad(audio, padding, mode='constant')
198
+ frames = spectrograms.split_audio(audio, self.spectrogram_config)
199
+ num_frames = len(audio) // frame_size
200
+ times = np.arange(num_frames) / self.spectrogram_config.frames_per_second
201
+ return frames, times
202
+
203
+ def preprocess(self, ds):
204
+ pp_chain = [
205
+ functools.partial(
206
+ t5.data.preprocessors.split_tokens_to_inputs_length,
207
+ sequence_length=self.sequence_length,
208
+ output_features=self.output_features,
209
+ feature_key='inputs',
210
+ additional_feature_keys=['input_times']),
211
+ # Cache occurs here during training.
212
+ preprocessors.add_dummy_targets,
213
+ functools.partial(
214
+ preprocessors.compute_spectrograms,
215
+ spectrogram_config=self.spectrogram_config)
216
+ ]
217
+ for pp in pp_chain:
218
+ ds = pp(ds)
219
+ return ds
220
+
221
+ def postprocess(self, tokens, example):
222
+ tokens = self._trim_eos(tokens)
223
+ start_time = example['input_times'][0]
224
+ # Round down to nearest symbolic token step.
225
+ start_time -= start_time % (1 / self.codec.steps_per_second)
226
+ return {
227
+ 'est_tokens': tokens,
228
+ 'start_time': start_time,
229
+ # Internal MT3 code expects raw inputs, not used here.
230
+ 'raw_inputs': []
231
+ }
232
+
233
+ @staticmethod
234
+ def _trim_eos(tokens):
235
+ tokens = np.array(tokens, np.int32)
236
+ if vocabularies.DECODED_EOS_ID in tokens:
237
+ tokens = tokens[:np.argmax(tokens == vocabularies.DECODED_EOS_ID)]
238
+ return tokens
239
+
nvidia-container-runtime-script.sh ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # nvidia-container-runtime-script.sh
2
+
3
+ sudo curl -s -L https://nvidia.github.io/nvidia-container-runtime/gpgkey | \
4
+ sudo apt-key add -
5
+ distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
6
+ sudo curl -s -L https://nvidia.github.io/nvidia-container-runtime/$distribution/nvidia-container-runtime.list | \
7
+ sudo tee /etc/apt/sources.list.d/nvidia-container-runtime.list
8
+ sudo apt-get update
packages.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ libfluidsynth2
2
+ build-essential
3
+ libasound2-dev
4
+ libjack-dev
requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ nest-asyncio
2
+ pyfluidsynth
3
+ absl-py == 1.3.0
4
+ ddsp == 3.5.0
5
+ flax == 0.6.3
6
+ gin-config == 0.5.0
7
+ immutabledict == 2.2.3
8
+ librosa == 0.9.2
9
+ mir_eval == 0.7
10
+ note_seq == 0.0.3
11
+ numpy == 1.23.5
12
+ pretty_midi == 0.2.9
13
+ scikit-learn == 1.2.0
14
+ scipy == 1.10.0
15
+ seqio == 0.0.14
16
+ t5 == 0.9.3
17
+ tensorflow_cpu
18
+ tensorflow-datasets == 4.8.1
19
+