MusicLang API

class maidi.integrations.api.MusicLangAPI(api_key=None, api_url='https://api.musiclang.io', verbose=False)

Bases: MidiApiIntegration

Class to interact with the MusicLang API from a maidi.MidiScore

Usage:

>>> import os
>>> import numpy as np
>>> API_URL = os.getenv("API_URL")
>>> MUSICLANG_API_KEY = os.getenv("MUSICLANG_API_KEY")
>>> from maidi.integrations.api import MusicLangAPI
>>> from maidi import MidiScore,instrument
>>> api = MusicLangAPI(API_URL, MUSICLANG_API_KEY)
>>> score = MidiScore.from_empty(instruments=[instrument.PIANO, instrument.ELECTRIC_BASS_FINGER], nb_bars=4, ts=(4, 4), tempo=120)
>>> mask = np.ones((2, 4))
>>> predicted_score = api.predict(score, mask, model="control_masking_large", timeout=120, temperature=0.95)
>>> predicted_score.write("predicted_score.mid")
__init__(api_key=None, api_url='https://api.musiclang.io', verbose=False)

Initialize the MusicLangAPI class

Parameters:
  • api_url (str) – URL of the API

  • api_key (str) – Your secret API key to use

  • verbose (bool) – If True, print debug information (Default value = False)

check_parameters(score, mask, model='control_masking_large', temperature=0.95, polling_interval=1, tags=None, chords=None, **kwargs)
create_transition(score1, score2, nb_bars_transition, model='control_masking_large', return_all=True, chords=None, tags=None, timeout=120, temperature=0.95, async_mode=False, polling_interval=1, **prediction_kwargs)

Create a transition between two scores using the MusicLang API.

Parameters:
  • score1 (MidiScore) – The initial score from which to transition.

  • score2 (MidiScore) – The final score to transition to.

  • nb_bars_transition (int) – The number of bars to use for the transition.

  • model (str, optional) – The model to use for the transition (default is “control_masking_large”).

  • return_all (bool, optional) – If True, return the full concatenated score with transition, otherwise only the transition part (default is True).

  • chords (list[tuple or None], optional) – List of chord tuples to guide the transition.

  • tags (list[list[list]], optional) – Tags to guide the transition, provided as a list of lists for each track and bar.

  • timeout (int, optional) – Timeout for the API call (default is 120 seconds).

  • temperature (float, optional) – Temperature parameter for the model (default is 0.95).

  • async_mode (bool, optional) – If True, return the task id, otherwise wait for the request to finish with polling (default is False).

  • polling_interval (int, optional) – Interval in seconds to poll the API for completion (default is 1 second).

Returns:

The score with the transition bars added, or only the transition part based on the return_all parameter.

Return type:

MidiScore

Raises:

ValueError – If the model is not recognized or if the input parameters are invalid.

create_variation(midi_path, temperature=0.6, **predict_kwargs)

Create a variation of the given MIDI file using the MusicLang API. The midi file can be of any length. It will generate a score constrained by the tags and the chord progression of the original file It can be useful if you want to generate new ideas from an existing piece of music.

Parameters:
  • midi_path (str) – The path of the midi file you want to create a variation on

  • temperature (float) – The temperature for the model (default is 0.6)

  • **predict_kwargs – Additional arguments to be passed to the predict method

extend(score, nb_bars_added, model='control_masking_large', nb_added_bars_step=None, chords=None, tags=None, timeout=120, temperature=0.95, polling_interval=1, **prediction_kwargs)

Extend the given score by a specified number of bars using the MusicLang API.

Parameters:
  • score (MidiScore) – The initial score to extend.

  • nb_bars_added (int) – The number of bars to add to the score.

  • model (str, optional) – The model to use for the extension (default is “control_masking_large”).

  • nb_added_bars_step (int, optional) – Number of bars to add in each step (if None, the extension will use the maximum context size).

  • chords (list[tuple or None], optional) – List of chord tuples to guide the extension.

  • tags (list[list[list]], optional) – Tags to guide the extension, provided as a list of lists for each track and bar.

  • timeout (int, optional) – Timeout for the API call (default is 120 seconds).

  • temperature (float, optional) – Temperature parameter for the model (default is 0.95).

  • polling_interval (int, optional) – Interval in seconds to poll the API for completion (default is 1 second).

  • **prediction_kwargs (dict) – Additional arguments for the model

Returns:

The extended score with the specified number of additional bars.

Return type:

MidiScore

Raises:

ValueError – If the model is not recognized or if the input parameters are invalid.

from_task_id(task_id, polling_interval=1, timeout=3000)

Create a score from a task id by calling the API polling endpoint each polling_interval seconds until completion or failure.

Usage

>>> import numpy as np
>>> import time
>>> from maidi import MidiScore
>>> from maidi.integrations.api import MusicLangAPI
>>> score = MidiScore.from_empty(instruments=['piano'], nb_bars=4, ts=(4, 4), tempo=120)
>>> mask = np.ones((1, 4))
>>> api = MusicLangAPI(API_URL, MUSICLANG_API_KEY)
>>> task_id = api.predict(score, mask, async_mode=True)
>>> score = api.from_task_id(task_id, polling_interval=3) # Wait for the task to complete by polling the API every 3 seconds
Parameters:
  • task_id – str, task identifier you got from the predict call

  • polling_interval – int, interval in seconds to poll the API (Default value = 1)

  • timeout – int, timeout in seconds, raise an error if the task is not completed after this time (Default value = 3000)

generate_from_scratch(instruments, nb_bars, ts, tempo, model='control_masking_large', chords=None, tags=None, temperature=0.95, **kwargs)

Generate a score from scratch with the given parameters

Parameters:
  • instruments (list[str]) – List of instruments to use

  • nb_bars (int) – Number of bars

  • ts (tuple) – Time signature

  • tempo (int) – Tempo

  • model (str) – Model to use (Default value = models.MODEL_CONTROL_MASKING_LARGE)

  • chords (list[tuple or None]) – List of chord tuples to guide the generation

  • tags (list[list[list]] or None) – Tags to guide the generation

  • temperature (float) – Temperature for the model (Default value = 0.95)

  • **kwargs – Additional arguments for the model to pass to the predict method

  • **Usage**

  • np (>>> import numpy as)

  • MidiScore (>>> from maidi import)

  • instrument

  • MusicLangAPI (>>> from maidi.integrations.api import)

  • models (>>> from maidi.integrations.api.musiclang import)

  • MusicLangAPI(API_URL (>>> api =)

  • MUSICLANG_API_KEY)

  • api.generate_from_scratch(instruments=[instrument.ELECTRIC_PIANO (>>> score =)

  • instrument.ALTO_SAX]

  • nb_bars=4

  • ts=(4

  • 4)

  • tempo=120

  • model=models.MODEL_CONTROL_MASKING_LARGE

  • temperature=0.95)

  • score.write("generated_score.mid") (>>>)

poll_api(task_id)

Poll the API with a task id once

Parameters:

task_id – str, task identifier you got from the predict call

Returns:

result

Return type:

None or MidiScore

Raises:

ValueError – Task failed

predict(score, mask, model='control_masking_large', timeout=120, temperature=0.95, cut_silenced_bars=False, regen_missing_bars=False, async_mode=False, polling_interval=1, tags=None, chords=None, **prediction_kwargs)

Predict the score with the given mask and prediction parameters

Usage

>>> import numpy as np
>>> from maidi import MidiScore
>>> from maidi.integrations.api import MusicLangAPI
>>> score = MidiScore.from_empty(instruments=['piano'], nb_bars=4, ts=(4, 4), tempo=120)
>>> mask = np.ones((1, 4))
>>> api = MusicLangAPI(API_URL, MUSICLANG_API_KEY)  # Get your API_URL and MUSICLANG_API_KEY here
>>> predicted_score = api.predict(score, mask, model="control_masking_large", timeout=120, temperature=0.95)
>>> predicted_score.write("predicted_score.mid")
Parameters:
  • score (MidiScore) – The score to predict

  • mask (np.array of shape (n_tracks, n_bars)) – The mask to use for the prediction

  • model – str, model to use (for the API) (Default value = “control_masking_large”)

  • timeout – int, timeout for the API (Default value = 120)

  • temperature – float, temperature for the model (Default value = 0.95)

  • cut_silenced_bars – bool, if True cut silenced bars at the beginning and end (Default value = False)

  • regen_missing_bars – bool, if True regenerate missing bars with another call to predict (Default value = False)

  • prediction_kwargs – dict, additional arguments for the model (specifically chord and control tags)

  • async_mode – bool, if True return the task id, otherwise wait for the request to finish with polling (Default value = False)

  • polling_interval – int, interval in seconds to poll the API, only used if async_mode is False (Default value = 1)

  • chords (list[tuple or None ] or str or None) – List of tuple (chord_degree, tonality_degree, tonality_mode, roman numeral extension). Check the user guide for more information. Can also be passed as a roman numeral string that can have “x” instead of chord to let the model choose (Eg : “c: i iv x i”)

  • tags (list[list[list]] or None (n_tracks, n_bars, <variable length number of tags>)) – Way to specify soft constraints on the generation for each bar of each track, check the user guide for more information

  • **prediction_kwargs

Returns:

MidiScore or str : predicted score if sync mode

Return type:

score

sanitize_score(score, score_to_compare, mask)

Do checks after predicting a score

Parameters:
  • score – param score_to_compare:

  • mask – return:

  • score_to_compare (MidiScore)

MAX_CONTEXT = 16
POLLING_ENDPOINT = 'polling_predict'
PREDICT_ASYNC_ENDPOINT = 'predict_long'
PREDICT_SYNC_ENDPOINT = 'predict'