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