basic-pitch

repository·main·Indexed 26 days ago

https://github.com/spotify/basic-pitch

A lightweight, instrument-agnostic Python library for Automatic Music Transcription (AMT) that converts polyphonic audio into MIDI files, including pitch bend detection. It supports multiple runtimes including TensorFlow, CoreML, TensorFlowLite, and ONNX, and provides both a CLI and a Python API for audio-to-MIDI conversion.

Tokens
5.6K
Snippets
9
Records
36
Agent score
90%

What's inside basic-pitch

  1. Install basic-pitch via pip

    main

    Install the current release of basic-pitch using pip. To update to the latest version, use the --upgrade flag.

    Compatible Environments:

    • OS: macOS, Windows, and Ubuntu
    • Python: 3.7, 3.8, 3.9, 3.10, 3.11
    • Note for Mac M1: Only Python 3.10 is currently supported; otherwise, use a virtual machine.
    pip install basic-pitch
  2. Install basic-pitch with TensorFlow runtime

    main

    By default, basic-pitch does not install TensorFlow to save time and space. It installs platform-specific runtimes (CoreML on macOS, TensorFlowLite on Linux, ONNX on Windows). To explicitly install TensorFlow along with the default model inference runtime, use the [tf] extra.

    pip install basic-pitch[tf]
  3. Download and process datasets for training

    main

    Use the scripts located in the datasets folder to download and process datasets for training the Basic Pitch model. These scripts utilize Apache Beam pipelines to handle data processing.

    When running these scripts, you can specify several keyword arguments to control data storage, processing methods, and partitioning.

  4. Install specific model runtimes for basic-pitch

    main

    Depending on which model format you intend to use, you may need to install additional dependencies. If you encounter warnings about missing runtimes, use the following commands:

    • CoreML: pip install 'basic-pitch[coreml]'
    • TensorFlow / TFLite: pip install 'basic-pitch[tf]' or pip install 'basic-pitch tflite-runtime'
    • ONNX: pip install 'basic-pitch[onnx]'
  5. Run prediction in a loop with a loaded Model

    main

    To avoid the overhead of reloading the model for every file, load the Model object once and pass it to the predict() function inside your loop.

    import tensorflow as tf
    
    from basic_pitch.inference import predict, Model
    from basic_pitch import ICASSP_2022_MODEL_PATH
    
    basic_pitch_model = Model(ICASSP_2022_MODEL_PATH)
    
    for x in range():
        model_output, midi_data, note_events = predict(
            <loop-x-input-audio-path>,
            basic_pitch_model,
        )
  6. Predict audio using predict()

    main

    Import predict from basic_pitch.inference to run transcription directly in Python.

    Signature: model_output, midi_data, note_events = predict(<input-audio-path>, [basic_pitch_model])

    Returns:

    • model_output: The raw model inference output.
    • midi_data: The transcribed MIDI data derived from the output.
    • note_events: A list of note events derived from the output.

    Note: You can pass an optional basic_pitch_model object to avoid reloading the model on every call, which is recommended when running in a loop.

    from basic_pitch.inference import predict
    from basic_pitch import ICASSP_2022_MODEL_PATH
    
    model_output, midi_data, note_events = predict(<input-audio-path>)
  7. Orchestrate transcription and file saving with predict_and_save()

    main

    Use predict_and_save to automatically handle the generation and saving of various output file types (MIDI, WAV, NPZ, CSV).

    from basic_pitch.inference import predict_and_save
    
    predict_and_save(
        <input-audio-path-list>,
        <output-directory>,
        <save-midi>,
        <sonify-midi>,
        <save-model-outputs>,
        <save-notes>,
        <model-path>
    )
  8. Reference arguments for dataset download scripts

    main

    The following arguments are available for the dataset download and processing scripts in the datasets folder:

    ArgumentDescription
    --sourceSource directory to download raw data to. Defaults to $HOME/mir_datasets/{dataset_name}.
    --destinationDirectory to write processed data to. Defaults to $HOME/data/basic_pitch/{dataset_name}.
    --runnerThe method used to run the Beam Pipeline. Options: DirectRunner (local process), PortableRunner (local Docker container), or DataflowRunner (Google Cloud Dataflow).
    --timestampedIf passed, the dataset is placed into a timestamped directory instead of the splits directory.
    --batch-sizeNumber of examples per tfrecord when partitioning the dataset.
    --sdk_container_imageThe Docker container image used if using PortableRunner.
    --job_endpointThe endpoint where the job is running. Defaults to embed (works for PortableRunner).

    Note for DataflowRunner users: You must provide the following Google Cloud Storage (GCS) and project configuration arguments:

    • --temp_location={Path to GCS Bucket}
    • --staging_location={Path to GCS Bucket}
    • --project={Name of GCS Project}
    • --region={GCS region}
  9. Supported audio input formats

    main

    Basic Pitch accepts audio files compatible with librosa.

    Supported Codecs:

    • .mp3
    • .ogg
    • .wav
    • .flac
    • .m4a

    Processing Details:

    • Channels: While stereo is accepted, input is down-mixed to mono for analysis.
    • Sample Rate: All audio is resampled to 22050 Hz.
    • Length: Can process any length, but very large files may be limited by disk space; streaming in windows is recommended for long files.
  10. Reference: predict_and_save() arguments

    main

    The predict_and_save function accepts the following arguments:

    • <input-audio-path-list>: Directory paths for basic-pitch to read from.
    • <output-directory>: Directory path to write results to.
    • <save-midi> (bool): Control generating and saving a MIDI file.
    • <sonify-midi> (bool): Control saving a WAV audio rendering of the MIDI file.
    • <save-model-outputs> (bool): Control saving the raw model output as an NPZ file.
    • <save-notes> (bool): Control saving predicted note events as a CSV file.
    • <model-path> (str or pathlib.Path): Local path to load the model from (e.g., use ICASSP_2022_MODEL_PATH).
  11. Use the basic-pitch CLI

    main

    The command line tool generates a MIDI file transcription of audio files.

    Basic Usage:

    basic-pitch <output-directory> <input-audio-path>

    To process multiple files at once:

    basic-pitch <output-directory> <input-audio-path-1> <input-audio-path-2> <input-audio-path-3>

    CLI Flags:

    • --sonify-midi: Save a .wav audio rendering of the MIDI file.
    • --save-model-outputs: Save raw model outputs as an .npz file.
    • --save-note-events: Save predicted note events as a .csv file.
    • --model-serialization: Specify a non-default model type (e.g., use CoreML instead of TF).
    • --help: Discover all available parameter controls.
    basic-pitch <output-directory> <input-audio-path>
  12. Run full audio transcription with `predict()`

    main

    The predict() function is the primary high-level API for transcribing an audio file into MIDI and note events. It handles audio loading, windowing, inference, and post-processing.

    Arguments:

    • audio_path (Union[pathlib.Path, str]): Path to the input audio file.
    • model_or_model_path (Union[Model, pathlib.Path, str]): A loaded Model instance or a path to a serialized model.
    • onset_threshold (float): Minimum energy for an onset (default: 0.5).
    • frame_threshold (float): Minimum energy for a frame (default: 0.3).
    • minimum_note_length (float): Minimum note length in milliseconds (default: 127.7).
    • minimum_frequency (Optional[float]): Minimum output frequency in Hz.
    • maximum_frequency (Optional[float]): Maximum output frequency in Hz.
    • multiple_pitch_bends (bool): If True, allows overlapping notes in MIDI to have pitch bends.
    • melodia_trick (bool): Whether to use the Melodia post-processing step.
    • midi_tempo (float): MIDI tempo (default: 120).
    • debug_file (Optional[pathlib.Path]): Path to save debug JSON data.

    Returns: A tuple containing:

    1. model_output: A dictionary of raw model predictions (note, onset, contour).
    2. midi_data: A pretty_midi.PrettyMIDI object.
    3. note_events: A list of note event tuples: (start_time_s, end_time_s, pitch_midi, velocity, [pitch_bend_values]).