Hmjz100 mdnestor commited on
Commit
8559b66
·
0 Parent(s):

Duplicate from mdnestor/YouTube-to-MT3

Browse files

Co-authored-by: mdnestor <[email protected]>

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