fix this script  :# Setup Environment
!apt-get update -qq && apt-get install -qq libfluidsynth3 build-essential libasound2-dev libjack-dev ffmpeg

# Install required packages
!pip install --quiet spotdl==4.2.8

# Clone MT3 repository
!git clone --branch=main https://github.com/magenta/mt3
%cd mt3

# Install MT3 and dependencies
!pip install --quiet jax[cuda12] nest-asyncio pyfluidsynth==1.3.0 pretty_midi noisereduce -e . -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html

# Copy checkpoints and soundfont
!gsutil -q -m cp -r gs://mt3/checkpoints .
!gsutil -q -m cp gs://magentadata/soundfonts/SGM-v2.01-Sal-Guit-Bass-V1.3.sf2 .


# Imports and Definitions
import numpy as np
import tensorflow.compat.v2 as tf

import functools
import gin
import jax
import librosa
import note_seq
import seqio
import t5
import t5x

from mt3 import models
from mt3 import network
from mt3 import note_sequences
from mt3 import preprocessors
from mt3 import spectrograms
from mt3 import vocabularies
from mt3 import metrics_utils

import nest_asyncio
nest_asyncio.apply()

import os
import tempfile
import subprocess
import shutil
from google.colab import files

import pretty_midi  # For post-processing MIDI
import noisereduce as nr  # For noise reduction

SAMPLE_RATE = 16000
SF2_PATH = 'SGM-v2.01-Sal-Guit-Bass-V1.3.sf2'

def download_song(song_query):
    """Download song using spotdl."""
    tmpdirname = tempfile.mkdtemp()
    try:
        print("Starting song download...")
        subprocess.run([
            'spotdl', song_query,
            '--output', os.path.join(tmpdirname, '{artist} - {title}.{output-ext}')
        ], check=True)
        
        # Fetch the downloaded song
        downloaded_files = os.listdir(tmpdirname)
        if downloaded_files:
            song_file = os.path.join(tmpdirname, downloaded_files[0])
            print(f"Song downloaded successfully: {downloaded_files[0]}")
            return song_file, tmpdirname  # Return song path and temp directory
        else:
            print("Failed to download song.")
            return None, tmpdirname
    except subprocess.CalledProcessError as e:
        print(f"An error occurred while downloading the song: {e}")
        return None, tmpdirname

def clean_up(temp_dirs):
    """Clean up temporary directories."""
    for tmpdirname in temp_dirs:
        if os.path.exists(tmpdirname):
            shutil.rmtree(tmpdirname)
            print(f"Deleted temporary directory: {tmpdirname}")

def normalize_audio(y):
    """Normalize the audio signal to have consistent volume."""
    try:
        print("Normalizing audio...")
        y_norm = librosa.util.normalize(y)
        print("Audio normalization complete.")
        return y_norm
    except Exception as e:
        print(f"An error occurred during audio normalization: {e}")
        return y

def reduce_noise(y, sr):
    """Reduce noise in the audio signal using spectral gating."""
    try:
        print("Reducing noise using spectral gating...")
        # Estimate the noise sample. We'll take the first 0.5 seconds assuming it is noise.
        noise_duration = 0.5  # seconds
        noise_sample = y[:int(noise_duration * sr)]
        y_reduced_noise = nr.reduce_noise(y=y, sr=sr, y_noise=noise_sample, prop_decrease=1.0)
        print("Noise reduction complete.")
        return y_reduced_noise
    except Exception as e:
        print(f"An error occurred during noise reduction: {e}")
        return y

def post_process_midi(midi_file):
    """Adjust MIDI velocities, quantize notes, and remove short notes using pretty_midi."""
    try:
        print("Post-processing MIDI file to enhance quality...")
        midi_data = pretty_midi.PrettyMIDI(midi_file)
        
        # Get tempo changes (if any)
        tempo_changes_times, tempo_changes = midi_data.get_tempo_changes()
        
        # For simplicity, use the first tempo
        if len(tempo_changes) > 0:
            bpm = tempo_changes[0]
        else:
            bpm = 120  # Default tempo if no tempo changes are detected

        # Compute time per 32nd note for quantization
        quantization_unit = 60 / (bpm * 8)  # 32nd note duration in seconds

        # Set minimum note length to 0.1 seconds
        minimum_note_duration = 0.1  # seconds

        for instrument in midi_data.instruments:
            # Set all instruments to a piano sound
            instrument.program = pretty_midi.instrument_name_to_program('Acoustic Grand Piano')
            instrument.is_drum = False
            # Remove pitch bends and control changes
            instrument.pitch_bends = []
            instrument.control_changes = []

            # Process notes
            new_notes = []
            for note in instrument.notes:
                # Quantize note start and end times
                note.start = round(note.start / quantization_unit) * quantization_unit
                note.end = round(note.end / quantization_unit) * quantization_unit
                # Ensure note.end is after note.start
                if note.end <= note.start:
                    note.end = note.start + quantization_unit  # At least one quantization unit
                # Remove notes that are too short
                if (note.end - note.start) < minimum_note_duration:
                    continue  # Skip this note
                # Adjust velocities
                note.velocity = min(127, max(70, note.velocity))  # Reasonable velocity range
                new_notes.append(note)
            instrument.notes = new_notes  # Update notes for the instrument

        # Save the modified MIDI file
        midi_data.write(midi_file)
        print("MIDI post-processing complete. Enhanced MIDI saved.")
        
    except Exception as e:
        print(f"An error occurred during MIDI post-processing: {e}")

class InferenceModel(object):
    """Wrapper of T5X model for music transcription."""

    def __init__(self, checkpoint_path, model_type='mt3'):

        # Model Constants.
        if model_type == 'ismir2021':
            num_velocity_bins = 127
            self.encoding_spec = note_sequences.NoteEncodingSpec
            self.inputs_length = 512
        elif model_type == 'mt3':
            num_velocity_bins = 1
            self.encoding_spec = note_sequences.NoteEncodingWithTiesSpec
            self.inputs_length = 256
        else:
            raise ValueError('unknown model_type: %s' % model_type)

        gin_files = ['./mt3/gin/model.gin',
                     f'./mt3/gin/{model_type}.gin']

        self.batch_size = 8
        self.outputs_length = 1024
        self.sequence_length = {'inputs': self.inputs_length,
                                'targets': self.outputs_length}

        self.partitioner = t5x.partitioning.PjitPartitioner(num_partitions=1)

        # Build Codecs and Vocabularies.
        self.spectrogram_config = spectrograms.SpectrogramConfig()
        self.codec = vocabularies.build_codec(
            vocab_config=vocabularies.VocabularyConfig(
                num_velocity_bins=num_velocity_bins))
        self.vocabulary = vocabularies.vocabulary_from_codec(self.codec)
        self.output_features = {
            'inputs': seqio.ContinuousFeature(dtype=tf.float32, rank=2),
            'targets': seqio.Feature(vocabulary=self.vocabulary),
        }

        # Create a T5X model.
        self._parse_gin(gin_files)
        self.model = self._load_model()

        # Restore from checkpoint.
        self.restore_from_checkpoint(checkpoint_path)

    @property
    def input_shapes(self):
        return {
            'encoder_input_tokens': (self.batch_size, self.inputs_length),
            'decoder_input_tokens': (self.batch_size, self.outputs_length)
        }

    def _parse_gin(self, gin_files):
        """Parse gin files used to train the model."""
        gin_bindings = [
            'from __gin__ import dynamic_registration',
            'from mt3 import vocabularies',
            'VOCAB_CONFIG=@vocabularies.VocabularyConfig()',
            'vocabularies.VocabularyConfig.num_velocity_bins=%NUM_VELOCITY_BINS'
        ]
        with gin.unlock_config():
            gin.parse_config_files_and_bindings(
                gin_files, gin_bindings, finalize_config=False)

    def _load_model(self):
      """Load up a T5X `Model` after parsing training gin config."""
      model_config = gin.get_configurable(network.T5Config)()
      module = network.Transformer(config=model_config)
      return models.ContinuousInputsEncoderDecoderModel(
          module=module,
          input_vocabulary=self.output_features['inputs'].vocabulary,
          output_vocabulary=self.output_features['targets'].vocabulary,
          optimizer_def=t5x.adafactor.Adafactor(decay_rate=0.8, step_offset=0),
          input_depth=spectrograms.input_depth(self.spectrogram_config))

    def restore_from_checkpoint(self, checkpoint_path):
        """Restore training state from checkpoint."""
        train_state_initializer = t5x.utils.TrainStateInitializer(
            optimizer_def=self.model.optimizer_def,
            init_fn=self.model.get_initial_variables,
            input_shapes=self.input_shapes,
            partitioner=self.partitioner)

        restore_checkpoint_cfg = t5x.utils.RestoreCheckpointConfig(
            path=checkpoint_path, mode='specific', dtype='float32')

        train_state_axes = train_state_initializer.train_state_axes
        self._predict_fn = self._get_predict_fn(train_state_axes)
        self._train_state = train_state_initializer.from_checkpoint_or_scratch(
            [restore_checkpoint_cfg], init_rng=jax.random.PRNGKey(0))

    @functools.lru_cache()
    def _get_predict_fn(self, train_state_axes):
        """Generate a partitioned prediction function for decoding."""
        def partial_predict_fn(params, batch, decode_rng):
            return self.model.predict_batch_with_aux(
                params, batch, decoder_params={'decode_rng': None})
        return self.partitioner.partition(
            partial_predict_fn,
            in_axis_resources=(
                train_state_axes.params,
                t5x.partitioning.PartitionSpec('data',), None),
            out_axis_resources=t5x.partitioning.PartitionSpec('data',)
        )

    def predict_tokens(self, batch, seed=0):
        """Predict tokens from preprocessed dataset batch."""
        prediction, _ = self._predict_fn(
            self._train_state.params, batch, jax.random.PRNGKey(seed))
        return self.vocabulary.decode_tf(prediction).numpy()

    def __call__(self, audio):
        """Infer note sequence from audio samples."""
        ds = self.audio_to_dataset(audio)
        ds = self.preprocess(ds)

        model_ds = self.model.FEATURE_CONVERTER_CLS(pack=False)(
            ds, task_feature_lengths=self.sequence_length)
        model_ds = model_ds.batch(self.batch_size)

        inferences = (tokens for batch in model_ds.as_numpy_iterator()
                      for tokens in self.predict_tokens(batch))

        predictions = []
        for example, tokens in zip(ds.as_numpy_iterator(), inferences):
            predictions.append(self.postprocess(tokens, example))

        result = metrics_utils.event_predictions_to_ns(
            predictions, codec=self.codec, encoding_spec=self.encoding_spec)
        return result['est_ns']

    def audio_to_dataset(self, audio):
        """Create a TF Dataset of spectrograms from input audio."""
        frames, frame_times = self._audio_to_frames(audio)
        return tf.data.Dataset.from_tensors({
            'inputs': frames,
            'input_times': frame_times,
        })

    def _audio_to_frames(self, audio):
        """Compute spectrogram frames from audio."""
        frame_size = self.spectrogram_config.hop_width
        padding = [0, frame_size - len(audio) % frame_size]
        audio = np.pad(audio, padding, mode='constant')
        frames = spectrograms.split_audio(audio, self.spectrogram_config)
        num_frames = len(audio) // frame_size
        times = np.arange(num_frames) / self.spectrogram_config.frames_per_second
        return frames, times

    def preprocess(self, ds):
        pp_chain = [
            functools.partial(
                t5.data.preprocessors.split_tokens_to_inputs_length,
                sequence_length=self.sequence_length,
                output_features=self.output_features,
                feature_key='inputs',
                additional_feature_keys=['input_times']),
            preprocessors.add_dummy_targets,
            functools.partial(
                preprocessors.compute_spectrograms,
                spectrogram_config=self.spectrogram_config)
        ]
        for pp in pp_chain:
            ds = pp(ds)
        return ds

    def postprocess(self, tokens, example):
        tokens = self._trim_eos(tokens)
        start_time = example['input_times'][0]
        # Round down to nearest symbolic token step.
        start_time -= start_time % (1 / self.codec.steps_per_second)
        return {
            'est_tokens': tokens,
            'start_time': start_time,
            'raw_inputs': []
        }

    @staticmethod
    def _trim_eos(tokens):
        tokens = np.array(tokens, np.int32)
        if vocabularies.DECODED_EOS_ID in tokens:
            tokens = tokens[:np.argmax(tokens == vocabularies.DECODED_EOS_ID)]
        return tokens

# Load Model
MODEL = "ismir2021"  # Choose between "ismir2021" and "mt3"
checkpoint_path = f'./checkpoints/{MODEL}/'
inference_model = InferenceModel(checkpoint_path, MODEL)

# Download Audio
song_query = input("Enter the song title or Spotify/YouTube link: ")

downloaded_song, tmpdirname = download_song(song_query)
temp_dirs = []  # Keep track of temporary directories to clean up
temp_dirs.append(tmpdirname)

if downloaded_song:
    # Load audio
    print("Loading audio file...")
    audio, sr = librosa.load(downloaded_song, sr=SAMPLE_RATE)
    # If the audio is stereo, convert it to mono
    if len(audio.shape) > 1:
        audio = librosa.to_mono(audio)
    
    # Normalize audio
    audio = normalize_audio(audio)
    
    # Reduce noise
    audio = reduce_noise(audio, sr)

    # Transcribe Audio
    print("Transcribing audio to MIDI...")
    est_ns = inference_model(audio)
    
    # Post-process MIDI
    midi_filename = '/tmp/transcribed.mid'
    note_seq.sequence_proto_to_midi_file(est_ns, midi_filename)
    post_process_midi(midi_filename)

    # Load the post-processed MIDI
    est_ns = note_seq.midi_file_to_note_sequence(midi_filename)
    
    # Play and plot the sequence
    note_seq.play_sequence(est_ns, synth=note_seq.fluidsynth,
                           sample_rate=SAMPLE_RATE, sf2_path=SF2_PATH)
    note_seq.plot_sequence(est_ns)
    
    # Download MIDI Transcription
    files.download(midi_filename)
else:
    print("No audio to process.")

# Clean up temporary directories
clean_up(temp_dirs) ,,,, from this error : ---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-d4a3cc06adec> in <cell line: 332>()
    330 MODEL = "ismir2021"  # Choose between "ismir2021" and "mt3"
    331 checkpoint_path = f'./checkpoints/{MODEL}/'
--> 332 inference_model = InferenceModel(checkpoint_path, MODEL)
    333 
    334 # Download Audio

21 frames
/usr/local/lib/python3.10/dist-packages/jax/experimental/array_serialization/serialization.py in async_deserialize(user_in_sharding, tensorstore_spec, global_shape, dtype, byte_limiter, context, assume_metadata)
    362   dll = (user_in_sharding.device_local_layout
    363          if isinstance(user_in_sharding, Layout) else None)
--> 364   t = await ts.open(
    365       tensorstore_spec,
    366       open=True,

ValueError: Error parsing object member "base": Error parsing object member "kvstore": Invalid file path: "./checkpoints/ismir2021/target.decoder.layers_0.encoder_decoder_attention.key.kernel/" [source locations='tensorstore/internal/json_binding/json_binding.h:825\ntensorstore/internal/json_binding/json_binding.h:861\ntensorstore/internal/json_binding/json_binding.h:825\ntensorstore/internal/json_binding/json_binding.h:861\ntensorstore/internal/json_binding/json_binding.h:825\ntensorstore/internal/json_binding/json_binding.h:825']
 .. buatkan dengan benar dan lengkap