### Install MusPy Source: https://github.com/salu133445/muspy/blob/main/docs/getting_started.html Installs the MusPy library using pip. This is a prerequisite for using MusPy. ```shell pip install muspy ``` -------------------------------- ### Load and Print Music Data with MusPy Source: https://github.com/salu133445/muspy/blob/main/docs/getting_started.html Loads a music file (e.g., JSON) into a MusPy Music object and prints its representation. It requires the MusPy library to be installed and a music file to be present. ```python import muspy music = muspy.load("example.json") print(music) music.print() ``` -------------------------------- ### Import MusPy Library Source: https://github.com/salu133445/muspy/blob/main/doc/source/getting_started.rst This code snippet shows the necessary command to import the MusPy library into your Python environment, making its functionalities available for use. ```python import muspy ``` -------------------------------- ### Pretty Print Music Data with MusPy Source: https://github.com/salu133445/muspy/blob/main/doc/source/getting_started.rst This snippet illustrates how to use the `.print()` method of a MusPy Music object to display its data in a more structured and readable format, which is useful for debugging and understanding the data. ```python music.print() ``` -------------------------------- ### Access Music Object Attributes in MusPy Source: https://github.com/salu133445/muspy/blob/main/docs/getting_started.html Demonstrates how to access specific attributes of a MusPy Music object using dot notation and list comprehensions. This allows for programmatic extraction of musical information. ```python print(music.metadata.title) print(music.tempos[0].qpm) print([note.pitch for note in music.tracks[0].notes]) ``` -------------------------------- ### Extract Note Pitches from Music Track using MusPy Source: https://github.com/salu133445/muspy/blob/main/doc/source/getting_started.rst This example demonstrates how to iterate through the notes of a specific track within a MusPy Music object and extract a list of all note pitches. It utilizes list comprehension for concise data extraction. ```python print([note.pitch for note in music.tracks[0].notes]) ``` -------------------------------- ### Load and Print Music Data using MusPy Source: https://github.com/salu133445/muspy/blob/main/doc/source/getting_started.rst Demonstrates how to load a music file (e.g., a JSON file) into a MusPy Music object and print its contents to the console. This is a fundamental step for data manipulation within MusPy. ```python music = muspy.load("example.json") print(music) ``` -------------------------------- ### Access Music Data Components using Dot Notation in MusPy Source: https://github.com/salu133445/muspy/blob/main/doc/source/getting_started.rst Shows how to access specific attributes of a MusPy Music object using dot notation, such as retrieving the song title from metadata or the tempo (qpm) from the tempos list. This allows for targeted data extraction. ```python print(music.metadata.title) print(music.tempos[0].qpm) ``` -------------------------------- ### Lyric Class Initialization in Python Source: https://github.com/salu133445/muspy/blob/main/docs/classes/lyric.html Shows the basic initialization of the Lyric class in Python. It requires the start time and the lyric text as arguments. This is the fundamental way to create a Lyric object. ```python from muspy import Lyric # Initialize a Lyric object lyric = Lyric(time=120, lyric="This is a lyric.") # Access attributes print(f"Time: {lyric.time}") print(f"Lyric: {lyric.lyric}") ``` -------------------------------- ### Annotation Class Initialization and Attributes Source: https://github.com/salu133445/muspy/blob/main/docs/classes/annotation.html Demonstrates the initialization of the Annotation class with time, annotation data, and an optional group. It highlights the purpose of each attribute: 'time' for the start time in time steps, 'annotation' for the data itself, and 'group' for organization. ```python from muspy import Annotation # Example with time and annotation data annotation_obj = Annotation(time=100, annotation="Verse 1") # Example with time, annotation data, and group annotation_obj_grouped = Annotation(time=200, annotation="Chorus", group="Main Section") print(annotation_obj.time) # Output: 100 print(annotation_obj.annotation) # Output: Verse 1 print(annotation_obj.group) # Output: None print(annotation_obj_grouped.time) # Output: 200 print(annotation_obj_grouped.annotation) # Output: Chorus print(annotation_obj_grouped.group) # Output: Main Section ``` -------------------------------- ### Score Visualization with Muspy Source: https://context7.com/salu133445/muspy/llms.txt Renders a musical piece as traditional musical notation using Muspy. This function requires MuseScore to be installed on the system. It allows saving the score as an image file (PNG) or a PDF document. Requires Muspy and MuseScore. ```python import muspy # Load music music = muspy.read('song.mid') # Show score (requires MuseScore) muspy.show_score(music) # Save score as image muspy.show_score(music, path='score.png') # Save as PDF muspy.show_score(music, path='score.pdf') ``` -------------------------------- ### XML Element Text Extraction Utilities Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/inputs/musescore.html Utility functions for extracting text content from XML elements. Includes methods to get text, get required text, and get required attributes, with options to handle newlines. Raises MuseScoreError if required elements or attributes are missing. ```python def _get_text(element: Element, path: str, default: T = None, remove_newlines: bool = False) -> Union[str, T]: """Return the text of the first matching element.""" elem = element.find(path) if elem is not None and elem.text is not None: if remove_newlines: return " ".join(elem.text.splitlines()) return elem.text return default # type: ignore def _get_required(element: Element, path: str) -> Element: """Return a required child element of an element. Raise a MuseScoreError if not found. """ elem = element.find(path) if elem is None: raise MuseScoreError( f"Element `{path}` is required for an '{element.tag}' element." ) return elem def _get_required_attr(element: Element, attr: str) -> str: """Return a required attribute of an element. Raise a MuseScoreError if not found. """ attribute = element.get(attr) if attribute is None: raise MuseScoreError( f"Attribute '{attr}' is required for an '{element.tag}' element." ) return attribute def _get_required_text(element: Element, path: str, remove_newlines: bool = False) -> str: """Return a required text from a child element of an element. Raise a MuseScoreError otherwise. """ elem = _get_required(element, path) if elem.text is None: raise MuseScoreError( f"Text content '{path}' of an element '{element.tag}' must not be " "empty." ) if remove_newlines: return " ".join(elem.text.splitlines()) return elem.text ``` -------------------------------- ### Download and Manage Muspy Datasets Source: https://context7.com/salu133445/muspy/llms.txt Demonstrates how to access and manage built-in datasets using Muspy. This includes automatic downloading and processing of datasets like MAESTRO, Lakh MIDI, and NES Music Database. It also shows how to list available datasets and load individual pieces. ```python import muspy # MAESTRO Dataset V2 (piano performances) maestro = muspy.MAESTRODatasetV2( root='./data/maestro', download_and_extract=True ) print(f"Dataset size: {len(maestro)}") # Load specific piece music = maestro[0] print(f"Title: {music.metadata.title}") # Iterate through dataset for i, music in enumerate(maestro[:5]): print(f"{i}: {music.metadata.title}") # Lakh MIDI Dataset (large-scale MIDI collection) lmd = muspy.LakhMIDIDataset( root='./data/lmd', download_and_extract=True ) # NES Music Database (video game music) nes = muspy.NESMusicDatabase( root='./data/nes', download_and_extract=True ) # List all available datasets datasets = muspy.list_datasets() print(datasets) ``` -------------------------------- ### Tempo Class Constructor and Methods in Python Source: https://github.com/salu133445/muspy/blob/main/docs/classes/tempo.html Demonstrates the constructor and common methods for the muspy.Tempo class. This includes initialization with time and qpm, and utility methods for object manipulation and validation. Dependencies include the muspy library itself. ```python import muspy # Constructor tempo = muspy.Tempo(time=0, qpm=120.0) # Methods adjusted_tempo = tempo.adjust_time(lambda t: t + 10) copied_tempo = tempo.copy() deep_copied_tempo = tempo.deepcopy() fixed_type_tempo = tempo.fix_type() # Class Methods dict_data = {"time": 0, "qpm": 120.0} tempo_from_dict = muspy.Tempo.from_dict(dict_data) # Validation is_valid = tempo.is_valid() tempo.validate() ``` -------------------------------- ### Get Real End Time Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/core.html Calculates the end time in real-time for a Music object. ```APIDOC ## GET REAL END TIME ### Description Calculates the end time in real-time for a Music object. This includes tempos, key signatures, time signatures, note offsets, lyrics, and annotations. Assumes 120 qpm if no tempo information is available. ### Method GET ### Endpoint /get_real_end_time ### Parameters #### Query Parameters - **music** (Music) - Required - Object to inspect. - **is_sorted** (boolean) - Optional - Whether all the list attributes are sorted (default: False). ### Response #### Success Response (200) - **real_end_time** (float) - The end time in real-time. #### Response Example ```json { "real_end_time": 50.5 } ``` ``` -------------------------------- ### TensorFlow Integration with Muspy Datasets Source: https://context7.com/salu133445/muspy/llms.txt Facilitates the creation of TensorFlow datasets for machine learning training pipelines using Muspy datasets. This example demonstrates converting music to an event representation and then creating a `tf.data.Dataset` that can be batched and padded. Requires TensorFlow and Muspy. ```python import muspy import tensorflow as tf # Load dataset dataset = muspy.JSBChoralesDataset('./data/jsb', download_and_extract=True) # Create TensorFlow dataset def generator(): for music in dataset: # Convert to event representation events = muspy.to_event_representation( music, max_time_shift=100, velocity_bins=32 ) yield events tf_dataset = tf.data.Dataset.from_generator( generator, output_signature=tf.TensorSpec(shape=(None,), dtype=tf.int32) ) # Batch and pad sequences tf_dataset = tf_dataset.padded_batch( batch_size=32, padded_shapes=[None], padding_values=0 ) # Iterate for batch in tf_dataset.take(1): print(f"Batch shape: {batch.shape}") ``` -------------------------------- ### Get End Time Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/core.html Retrieves the time of the last event in a Music or Track object. ```APIDOC ## GET END TIME ### Description Retrieves the time of the last event in a Music or Track object. This includes tempos, key signatures, time signatures, note offsets, lyrics, and annotations. ### Method GET ### Endpoint /get_end_time ### Parameters #### Query Parameters - **obj** (Music | Track) - Required - Object to inspect. - **is_sorted** (boolean) - Optional - Whether all the list attributes are sorted (default: False). ### Response #### Success Response (200) - **end_time** (int) - The time of the last event. #### Response Example ```json { "end_time": 1000 } ``` ``` -------------------------------- ### muspy.Note Source: https://github.com/salu133445/muspy/blob/main/docs/doc/muspy.html Represents a musical note with pitch, start and end times, and associated methods. ```APIDOC ## muspy.Note Class ### Description A container for musical notes. ### Attributes - **pitch_str** (str) - Note pitch as a string. - **start** (float) - Start time of the note. - **end** (float) - End time of the note. ### Methods - **adjust_time(func, attr=None, recursive=True)**: Adjust the timing of the note. - **transpose(semitone)**: Transpose the note by a number of semitones. - **clip(lower=0, upper=127)**: Clip the velocity of the note. ``` -------------------------------- ### muspy.Track Methods Source: https://github.com/salu133445/muspy/blob/main/docs/classes/track.html Methods for Track objects, including getting the end time and printing. ```APIDOC ## Track.get_end_time() ### Description Returns the time of the last event, including notes, chords, lyrics, and annotations. ### Method GET_END_TIME (conceptual, as it's a method call) ### Parameters * **is_sorted** (bool, optional) - Whether all the list attributes are sorted. Defaults to False. ### Returns The time of the last event. ## Track.pretty_str() ### Description Returns the attributes as a string in a YAML-like format. ### Method PRETTY_STR (conceptual, as it's a method call) ### Parameters * **skip_missing** (bool, optional) - Whether to skip attributes with value None or those that are empty lists. Defaults to True. ### Returns Stored data as a string in a YAML-like format. ## Track.print() ### Description Prints the attributes in a YAML-like format. ### Method PRINT (conceptual, as it's a method call) ### Parameters * **skip_missing** (bool, optional) - Whether to skip attributes with value None or those that are empty lists. Defaults to True. ``` -------------------------------- ### Initialize NottinghamDatabase in Python Source: https://github.com/salu133445/muspy/blob/main/docs/doc/muspy.html Initializes the Nottingham Database. This class is a specific implementation for the Nottingham dataset. It inherits from muspy.Dataset and supports common dataset management tasks including data download, extraction, and format conversion. ```python class NottinghamDatabase(_root_, _download_and_extract=False, _overwrite=False, _cleanup=False, _convert=False, _kind='json', _n_jobs=1, _ignore_exceptions=True, _use_converted=None, _verbose=True): """Nottingham Database.""" pass ``` -------------------------------- ### muspy.FolderDataset.on_the_fly() Source: https://github.com/salu133445/muspy/blob/main/docs/doc/datasets.html Enables on-the-fly mode, converting data samples as they are accessed. ```APIDOC ## PUT /datasets/folder/on_the_fly ### Description Enables the on-the-fly conversion mode, meaning data samples will be converted to music objects when they are indexed. Returns the dataset object itself. ### Method PUT ### Endpoint /datasets/folder/on_the_fly ### Parameters None ### Request Example ```json { "message": "Enable on-the-fly conversion" } ``` ### Response #### Success Response (200) - **status** (string) - Message confirming the mode change. - **dataset_state** (string) - Indicates the current state (e.g., 'on_the_fly'). #### Response Example ```json { "status": "On-the-fly conversion mode enabled.", "dataset_state": "on_the_fly" } ``` ``` -------------------------------- ### Get Raw Filenames (Python) Source: https://github.com/salu133445/muspy/blob/main/docs/doc/datasets.html The `get_raw_filenames()` method returns a list of original filenames for the raw data within the dataset. This can be used to reference the source files before conversion. ```python raw_files = dataset.get_raw_filenames() ``` -------------------------------- ### Initialize MusicDataset (Python) Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/datasets/base.html Initializes a MusicDataset, specifying the root directory and optionally the file kind (JSON or YAML). It creates the root directory if it doesn't exist and populates the `filenames` attribute by searching for specified file extensions using `_get_filenames`. Handles potential errors for invalid `kind` values. ```python def __init__(self, root: Union[str, Path], kind: str = None): if kind is not None and kind not in ("json", "yaml"): raise ValueError(f"Unknown value for `kind` : {kind} .") self.root = Path(root).expanduser().resolve() self.root.mkdir(exist_ok=True) if kind is None: extensions = ["json", "json.gz", "yaml", "yaml.gz"] elif kind == "json": extensions = ["json", "json.gz"] else: extensions = ["yaml", "yaml.gz"] self.filenames = _get_filenames(self.root, extensions) ``` -------------------------------- ### Get Converted Filenames (Python) Source: https://github.com/salu133445/muspy/blob/main/docs/doc/datasets.html The `get_converted_filenames()` method returns a list of filenames for the data that has already been converted and saved. This is useful for iterating over or managing existing converted data. ```python converted_files = dataset.get_converted_filenames() ``` -------------------------------- ### Tempo Class Source: https://github.com/salu133445/muspy/blob/main/docs/classes/tempo.html Represents tempo information within MusPy. It stores the start time of a tempo change and the tempo in quarter notes per minute (qpm). ```APIDOC ## Tempo Class ### Description The `muspy.Tempo` class is a container for tempo information, storing the start time and the tempo in quarter notes per minute (qpm). ### Attributes - **time** (int) - Start time of the tempo. - **qpm** (float) - Tempo in qpm (quarter notes per minute). ### Methods - **__init__(time, qpm)**: Initializes a Tempo object. - Parameters: - **time** (int) - Start time of the tempo, in time steps. - **qpm** (float) - Tempo in qpm (quarters per minute). - **adjust_time(func, attr=None, recursive=True)**: Adjusts the timing of time-stamped objects. - Parameters: - **func** (callable) – The function used to compute the new timing from the old timing, i.e., new_time = func(old_time). - **attr** (str, optional) – Attribute to adjust. Defaults to adjust all attributes. - **recursive** (bool, default: True) – Whether to apply recursively. - Returns: Object itself. - **copy()**: Returns a shallow copy of the object. - Returns: Shallow copy of the object. - **deepcopy()**: Returns a deep copy of the object. - Returns: Deep copy of the object. - **fix_type(attr=None, recursive=True)**: Fixes the types of attributes. - Parameters: - **attr** (str, optional) – Attribute to adjust. Defaults to adjust all attributes. - **recursive** (bool, default: True) – Whether to apply recursively. - Returns: Object itself. - **from_dict(dict__, strict=False, cast=False)**: Class method to return an instance constructed from a dictionary. - Parameters: - **dict__** (dict or mapping) – A dictionary that stores the attributes and their values. - **strict** (bool, default: False) – Whether to raise errors for invalid input types. - **cast** (bool, default: False) – Whether to cast types. - Returns: Constructed object. - **is_valid(attr=None, recursive=True)**: Returns True if an attribute has a valid type and value. - Parameters: - **attr** (str, optional) – Attribute to validate. Defaults to validate all attributes. - **recursive** (bool, default: True) – Whether to apply recursively. - Returns: bool – Whether the attribute has a valid type and value. - **validate()**: Raises an error if an attribute has an invalid type or value. ### Example ```python import muspy # Create a Tempo object tempo_obj = muspy.Tempo(time=0, qpm=120.0) # Access attributes print(f"Time: {tempo_obj.time}") print(f"QPM: {tempo_obj.qpm}") # Example of from_dict tempo_data = {'time': 100, 'qpm': 90.5} tempo_from_dict = muspy.Tempo.from_dict(tempo_data) print(f"Tempo from dict: time={tempo_from_dict.time}, qpm={tempo_from_dict.qpm}") ``` ### Response #### Success Response (200) - **time** (int) - The start time of the tempo. - **qpm** (float) - The tempo value in quarter notes per minute. #### Response Example ```json { "time": 0, "qpm": 120.0 } ``` ``` -------------------------------- ### Build Music Object Programmatically with MusPy Source: https://context7.com/salu133445/muspy/llms.txt Demonstrates how to construct a `Music` object from scratch in Python. This involves creating metadata, tempo, time signature, notes, and tracks programmatically, offering fine-grained control over the music composition. The resulting object can then be saved to standard formats like MIDI. ```python import muspy # Create metadata metadata = muspy.Metadata( title="Simple Melody", creators=["Composer Name"] ) # Create tempo (120 BPM) tempo = muspy.Tempo(time=0, qpm=120.0) # Create time signature (4/4) time_signature = muspy.TimeSignature(time=0, numerator=4, denominator=4) # Create notes (C major scale, quarter notes) notes = [] pitches = [60, 62, 64, 65, 67, 69, 71, 72] # C4 to C5 for i, pitch in enumerate(pitches): note = muspy.Note( time=i * 24, # 24 ticks per quarter note pitch=pitch, duration=24, velocity=80 ) notes.append(note) # Create track track = muspy.Track( program=0, # Acoustic Grand Piano is_drum=False, name="Piano", notes=notes ) # Assemble Music object music = muspy.Music( metadata=metadata, resolution=24, # Ticks per quarter note tempos=[tempo], time_signatures=[time_signature], tracks=[track] ) # Save as MIDI music.write_midi('simple_melody.mid') ``` -------------------------------- ### Initialize Lyric in muspy Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/classes.html Defines the Lyric class for storing lyrical content associated with a specific time in a musical piece. It includes the start time and the lyric string itself. ```python class Lyric(Base): """A container for lyrics. Attributes ---------- time : int Start time of the lyric, in time steps. lyric : str Lyric (sentence, word, syllable, etc.). """ _attributes = OrderedDict([("time", int), ("lyric", str)]) def __init__(self, time: int, lyric: str): self.time = time self.lyric = lyric ``` -------------------------------- ### Initialize MusicNetDataset in Python Source: https://github.com/salu133445/muspy/blob/main/docs/doc/muspy.html Initializes the MusicNet dataset, which is specific to MIDI files. It inherits from muspy.Dataset and supports downloading, extraction, and conversion of data. The 'kind' parameter specifies the data format, defaulting to JSON. ```python class MusicNetDataset(_root_, _download_and_extract=False, _overwrite=False, _cleanup=False, _convert=False, _kind='json', _n_jobs=1, _ignore_exceptions=True, _use_converted=None, _verbose=True): """MusicNet Dataset (MIDI only).""" pass ``` -------------------------------- ### Enable On-the-Fly Mode (Python) Source: https://github.com/salu133445/muspy/blob/main/docs/doc/datasets.html The `on_the_fly()` method enables the on-the-fly conversion mode. When enabled, data samples are converted to music objects as they are accessed, rather than requiring a separate conversion step beforehand. ```python dataset.on_the_fly() ``` -------------------------------- ### Get End Time of MusPy Objects Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/core.html Retrieves the end time of a MusPy object (Music, Track, or Note). This function is a wrapper around the get_end_time method of the respective objects. ```python from muspy.core import get_end_time # Example usage: # end_time = get_end_time(my_music) ``` -------------------------------- ### Initialize NESMusicDatabase in Python Source: https://github.com/salu133445/muspy/blob/main/docs/doc/muspy.html Initializes the NES Music Database. This class is designed to handle music data from the NES era. It supports standard dataset operations like downloading, extracting, and converting data, with 'kind' parameter defaulting to JSON. ```python class NESMusicDatabase(_root_, _download_and_extract=False, _overwrite=False, _cleanup=False, _convert=False, _kind='json', _n_jobs=1, _ignore_exceptions=True, _use_converted=None, _use_converted=None, _verbose=True): """NES Music Database.""" pass ``` -------------------------------- ### Handle MIDI Note On Messages in Python Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/inputs/midi.html Processes MIDI 'note_on' messages with velocity > 0 by recording the start time and velocity of active notes. Requires a dictionary `active_notes`. ```python elif msg.type == "note_on" and msg.velocity > 0: # Will later be closed by a note off message active_notes[(msg.channel, msg.note)].append( (time, msg.velocity) ) ``` -------------------------------- ### Display Piano-roll Visualization with MusPy Source: https://github.com/salu133445/muspy/blob/main/doc/source/visualization.rst Displays a piano-roll visualization of musical data using the Pypianoroll library. This function requires MusPy and Pypianoroll to be installed. It takes a MusPy object as input and renders it graphically. ```python import muspy # Assuming 'music' is a MusPy object muspy.show_pianoroll(music) ``` -------------------------------- ### Audio Synthesis with Muspy Source: https://context7.com/salu133445/muspy/llms.txt Synthesizes musical data into audio waveforms using Muspy. This process requires a soundfont (e.g., `.sf2` file) and optionally FluidSynth. The generated audio can be saved as a WAV file. Requires Muspy, NumPy, and SciPy. ```python import muspy import numpy as np from scipy.io import wavfile # Load music music = muspy.read('song.mid') # Synthesize to audio (requires FluidSynth) audio = muspy.synthesize(music, rate=44100) print(f"Audio shape: {audio.shape}") print(f"Duration: {len(audio)/44100:.2f} seconds") # Save to WAV file wavfile.write('output.wav', 44100, audio) # Or use write_audio directly music.write_audio('output.wav', rate=44100) # Specify soundfont music.write_audio('output.wav', rate=44100, soundfont='path/to/soundfont.sf2') ``` -------------------------------- ### Get MusicXML Divisions Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/inputs/musicxml.html Extracts a list of division values from the MusicXML structure. It iterates through 'part/measure/attributes/divisions' elements. This function raises a MusicXMLError if any division value is not an integer, as non-integer divisions are not supported. ```python def _get_divisions(root: Element): """Return a list of divisions.""" divisions = [] for division_elem in root.findall("part/measure/attributes/divisions"): if division_elem.text is None: continue if not float(division_elem.text).is_integer(): raise MusicXMLError( "Noninteger 'division' values are not supported." ) divisions.append(int(division_elem.text)) return divisions ``` -------------------------------- ### PyTorch Integration with Muspy Datasets Source: https://context7.com/salu133445/muspy/llms.txt Enables the creation of PyTorch datasets and dataloaders from Muspy datasets for machine learning model training. It includes a custom `collate_fn` to convert music objects to piano-roll representations and pad them to a uniform length. Requires PyTorch and Muspy. ```python import muspy import torch from torch.utils.data import DataLoader # Load dataset dataset = muspy.MAESTRODatasetV2('./data/maestro', download_and_extract=True) # Convert to piano-roll representation def collate_fn(music_list): pianorolls = [ muspy.to_pianoroll_representation(music, encode_velocity=False) for music in music_list ] # Pad to same length max_len = max(pr.shape[0] for pr in pianorolls) padded = torch.stack([ torch.nn.functional.pad( torch.from_numpy(pr), (0, 0, 0, max_len - pr.shape[0]) ) for pr in pianorolls ]) return padded.float() # Create dataloader dataloader = DataLoader( dataset, batch_size=8, shuffle=True, collate_fn=collate_fn, num_workers=4 ) # Training loop for batch in dataloader: print(f"Batch shape: {batch.shape}") # (batch_size, time, 128) # Train your model... break ``` -------------------------------- ### Initialize RemoteMusicDataset (Python) Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/datasets/base.html Initializes a RemoteMusicDataset, inheriting from both MusicDataset and RemoteDataset. It calls the constructors of both parent classes to set up remote dataset properties (like download/extract options) and music dataset properties (root directory, file kind). ```python def __init__( self, root: Union[str, Path], download_and_extract: bool = False, overwrite: bool = False, cleanup: bool = False, kind: str = None, verbose: bool = True, ): RemoteDataset.__init__( self, root, download_and_extract=download_and_extract, overwrite=overwrite, cleanup=cleanup, verbose=verbose, ) MusicDataset.__init__(self, root, kind=kind) ``` -------------------------------- ### Get Required Attribute from XML Element Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/inputs/musicxml.html Retrieves a required attribute value from an XML element. If the attribute is missing, it raises a `MusicXMLError`, indicating that the attribute is essential for the element's interpretation. ```python def _get_required_attr(element: Element, attr: str) -> str: """Return a required attribute; raise MusicXMLError if not found.""" attribute = element.get(attr) if attribute is None: raise MusicXMLError( f"Attribute '{attr}' is required for an '{element.tag}' element." ) return attribute ``` -------------------------------- ### Get Raw Filenames in FolderDataset Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/datasets/base.html Retrieves a sorted list of raw filenames from the root directory. It recursively searches for files with the specified extension, excluding any files located within a `_converted/` subdirectory. ```python def get_raw_filenames(self): """Return a list of raw filenames.""" return sorted( ( filename for filename in self.root.rglob("*." + self._extension) if not str(filename.relative_to(self.root)).startswith( "_converted/" ) ) ) ``` -------------------------------- ### Music21Dataset Initialization and Data Loading in Python Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/datasets/music21.html Initializes the Music21Dataset by either loading all files from the music21 corpus or filtering by a specific composer. It defines the file extensions to be considered and handles data loading. ```python class Music21Dataset(Dataset): """A class of datasets containing files in music21 corpus. Parameters ---------- composer : str Name of a composer or a collection. Please refer to the music21 corpus reference page for a full list [1]. References ---------- [1] https://web.mit.edu/music21/doc/about/referenceCorpus.html """ _info = DatasetInfo(_NAME, _DESCRIPTION, _HOMEPAGE) _citation = _CITATION _extensions = ( ".mid", ".midi", ".mxl", ".xml", ".mxml", ".musicxml", "# .abc", ) def __init__(self, composer: str = None): if composer is None: self.composer = "ALL" self.filenames = [ path for path in corpus.corpora.CoreCorpus().getPaths() if str(path).endswith(self._extensions) ] else: self.composer = composer self.filenames = corpus.getComposer(composer, self._extensions) def __repr__(self) -> str: return f"{type(self).__name__}(composer={self.composer})" def __getitem__(self, index) -> Music: if str(self.filenames[index]).lower().endswith(".abc"): return read(self.filenames[index], number=0) # type: ignore return read(self.filenames[index]) # type: ignore def __len__(self) -> int: return len(self.filenames) ``` -------------------------------- ### Write Music Object to MIDI, MusicXML, or Audio Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/outputs/wrappers.html Writes a MusPy Music object to a MIDI, MusicXML, or audio file. The output format is inferred from the file extension or specified using the 'kind' parameter. This function calls specific writers like `write_midi`, `write_musicxml`, and `write_audio`. Inputs include a file path and a Music object. Outputs are the written files. ```python def write( path: Union[str, Path], music: "Music", kind: str = None, **kwargs, ): """Write a Music object to a MIDI/MusicXML/ABC/audio file. Parameters ---------- path : str or Path Path to write the file. music : :class:`muspy.Music` Music object to convert. kind : {'midi', 'musicxml', 'abc', 'audio'}, optional Format to save. Defaults to infer from the extension. See Also -------- :func:`muspy.save` : Save a Music object loselessly to a JSON or a YAML file. """ if kind is None: if str(path).lower().endswith((".mid", ".midi")): kind = "midi" elif ( str(path).lower().endswith(( ".mxl", ".xml", ".mxml", ".musicxml") ) ): kind = "musicxml" elif str(path).lower().endswith(".abc"): kind = "abc" elif str(path).lower().endswith(( "wav", "aiff", "flac", "oga")): kind = "audio" else: raise ValueError( "Cannot infer file format from the extension (expect MIDI, " "MusicXML, ABC, WAV, AIFF, FLAC or OGA)." ) if kind.lower() == "midi": return write_midi(path, music, **kwargs) if kind.lower() == "musicxml": return write_musicxml(path, music, **kwargs) if kind.lower() == "audio": return write_audio(path, music, **kwargs) raise ValueError( ``` -------------------------------- ### Get Real End Time of MusPy Objects Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/core.html Retrieves the real end time of a MusPy object, considering potentially delayed events. This function wraps the get_real_end_time method of MusPy objects. ```python from muspy.core import get_real_end_time # Example usage: # real_end_time = get_real_end_time(my_track) ``` -------------------------------- ### Parse Marker-Measure Map from Staff XML (Python) Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/inputs/musescore.html Creates a dictionary mapping marker labels to their corresponding measure indices within a staff element. Initializes with a 'start' marker at measure 0. ```python def parse_marker_measure_map(elem: Element) -> Dict[str, int]: """Return a marker-measure map parsed from a staff element.""" # Initialize with a start marker markers: Dict[str, int] = {"start": 0} # Find all markers in all measures for i, measure_elem in enumerate(elem.findall("Measure")): for marker_elem in measure_elem.findall("Marker"): label = _get_text(marker_elem, "label") if label is not None: markers[label] = i return markers ``` -------------------------------- ### Initialize HymnalTuneDataset in Python Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/datasets/hymnal.html Initializes the HymnalTuneDataset, which manages tune-only MIDI files from hymnal.net. It checks for the existence of the root directory and optionally downloads the dataset. Dependencies include 'muspy' and 'pathlib'. It takes parameters for root directory, download, conversion, data kind, number of jobs, exception handling, and using converted files. ```python from muspy.datasets import HymnalTuneDataset hymnal_dataset = HymnalTuneDataset(root='/path/to/hymnal_tunes', download=True, convert=True) ``` -------------------------------- ### Read MIDI File with MusPy Source: https://context7.com/salu133445/muspy/llms.txt Loads a MIDI file into MusPy's universal Music object. It allows access to metadata like title and creators, tempo information, and details about tracks and notes within the file. No external dependencies beyond MusPy are required for reading. ```python import muspy # Read MIDI file music = muspy.read_midi('path/to/file.midi') # Access metadata print(music.metadata.title) print(music.metadata.creators) # Access tempo information print(f"First tempo: {music.tempos[0].qpm} BPM at time {music.tempos[0].time}") # Access tracks and notes for track in music.tracks: print(f"Track: {track.name}, Program: {track.program}, Notes: {len(track.notes)}") for note in track.notes[:5]: # First 5 notes print(f" Pitch: {note.pitch}, Time: {note.time}, Duration: {note.duration}, Velocity: {note.velocity}") ``` -------------------------------- ### MusicDataset Initialization Source: https://github.com/salu133445/muspy/blob/main/docs/doc/muspy.html Initializes a MusicDataset for accessing MusPy JSON/YAML files. ```APIDOC ## POST /datasets/muspy/initialize ### Description Initializes a MusicDataset for accessing MusPy JSON/YAML files. ### Method POST ### Endpoint /datasets/muspy/initialize ### Parameters #### Request Body - **root** (string) - Required - Root directory of the dataset. - **kind** (string) - Optional - File formats to include in the dataset. Defaults to include both JSON and YAML files. Allowed values: 'json', 'yaml'. ### Request Example ```json { "root": "/path/to/muspy/dataset", "kind": "json" } ``` ### Response #### Success Response (200) - **dataset_id** (string) - An identifier for the initialized dataset. #### Response Example ```json { "dataset_id": "muspy_data_json" } ``` ``` -------------------------------- ### Copy Beat Object in Python Source: https://github.com/salu133445/muspy/blob/main/docs/classes/beat.html Provides examples for creating shallow and deep copies of a Beat object. `copy()` creates a shallow copy, while `deepcopy()` creates a complete independent copy. ```python shallow_copy = beat_instance.copy() deep_copy = beat_instance.deepcopy() ``` -------------------------------- ### Initialize RemoteDataset in Python Source: https://github.com/salu133445/muspy/blob/main/docs/doc/muspy.html Initializes a remote MusPy dataset. It handles downloading and extracting data from specified URLs. Dependencies include the 'muspy' library. It takes the root directory as input and has options for downloading, overwriting, cleanup, and verbosity. ```python class RemoteDataset(_root_, _download_and_extract=False, _overwrite=False, _cleanup=False, _verbose=True): """Base class for remote MusPy datasets.""" pass ``` -------------------------------- ### Get Converted Filenames in FolderDataset Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/datasets/base.html Retrieves a sorted list of filenames for converted data within a specified directory and file kind. It utilizes `rglob` to recursively find files matching the pattern `*.{kind}`. ```python def get_converted_filenames(self): """Return a list of converted filenames.""" return sorted(self.converted_dir.rglob("*." + self.kind)) ``` -------------------------------- ### Muspy Music Object Visualization and Synthesis Source: https://github.com/salu133445/muspy/blob/main/docs/doc/muspy.html Methods for visualizing and synthesizing Muspy Music objects. ```APIDOC ## Music Object Visualization and Synthesis ### Show Visualization Displays a visualization of the Music object. **Parameters:** - `kind` (str) - The type of visualization to show. - `**kwargs` - Additional keyword arguments for visualization. **Method:** Any (internally called on a Music object) **Endpoint:** N/A (method within a class) ### Show Score Visualization Displays a score visualization of the Music object. **Parameters:** - `**kwargs` - Additional keyword arguments for visualization. **Method:** Any (internally called on a Music object) **Endpoint:** N/A (method within a class) ### Show Piano-roll Visualization Displays a piano-roll visualization of the Music object. **Parameters:** - `**kwargs` - Additional keyword arguments for visualization. **Method:** Any (internally called on a Music object) **Endpoint:** N/A (method within a class) ### Synthesize Audio Synthesizes the Music object into raw audio. **Parameters:** - `**kwargs` - Additional keyword arguments for synthesis. **Method:** Any (internally called on a Music object) **Endpoint:** N/A (method within a class) ``` -------------------------------- ### Parse Beats from MusicXML Measure Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/inputs/musicxml.html Calculates and appends beat information (including downbeats) for a given measure based on time signature and resolution. It determines beat start times and appends individual beats. ```python def parse_beats(measure_elem: Element, resolution: int, time_signature: TimeSignature) -> List[Beat]: beats: List[Beat] = [] beat_resolution: int = resolution * time_signature.numerator // time_signature.denominator time: int = 0 downbeat_times: List[int] = [] # Collect the measure start times downbeat_times.append(time) # Append the downbeat start = int(round(downbeat_times[0])) beats.append(Beat(time=start, is_downbeat=True)) # Append beats beat_times = np.arange(start + beat_resolution, time + beat_resolution * time_signature.numerator, beat_resolution) for beat_time in beat_times: beats.append(Beat(time=int(round(beat_time)), is_downbeat=False)) return beats ``` -------------------------------- ### muspy.inputs.from_pretty_midi Source: https://github.com/salu133445/muspy/blob/main/docs/doc/inputs.html Converts a pretty_midi.PrettyMIDI object into a Muspy Music object. ```APIDOC ## muspy.inputs.from_pretty_midi ### Description Return a pretty_midi PrettyMIDI object as a Music object. ### Method POST ### Endpoint /muspy/inputs/from_pretty_midi ### Parameters #### Path Parameters None #### Query Parameters * **midi** (PrettyMIDI) - Required - PrettyMIDI object to convert. * **resolution** (int) - Optional - Time steps per quarter note. Defaults to muspy.DEFAULT_RESOLUTION (24). ### Request Example ```json { "midi": "", "resolution": 24 } ``` ### Response #### Success Response (200) * **music** (muspy.Music) - Converted Music object. #### Response Example ```json { "music": "" } ``` ``` -------------------------------- ### Get Required XML Element Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/inputs/musicxml.html Retrieves a required XML element from a parent element using a specified path. If the element is not found, it raises a `MusicXMLError` indicating that the element is mandatory for the parent element's structure. ```python def _get_required(element: Element, path: str) -> Element: """Return a required element; raise ValueError if not found.""" elem = element.find(path) if elem is None: raise MusicXMLError( f"Element `'{path}'` is required for an '{element.tag}' element." ) return elem ``` -------------------------------- ### muspy.inputs.load Source: https://github.com/salu133445/muspy/blob/main/docs/doc/inputs.html Loads a Music object from a JSON or YAML file. ```APIDOC ## muspy.inputs.load ### Description Load a JSON or a YAML file into a Music object. This is a wrapper function for `muspy.load_json()` and `muspy.load_yaml()`. ### Method GET ### Endpoint /muspy/inputs/load ### Parameters #### Path Parameters None #### Query Parameters * **path** (str or Path or TextIO) - Required - Path to the file or the file to load. * **kind** (str) - Optional - Format to load. Defaults to infer from the extension ('json' or 'yaml'). * **kwargs** - Optional - Keyword arguments to pass to `muspy.load_json()` or `muspy.load_yaml()`. ### Request Example ```json { "path": "/path/to/your/music.json", "kind": "json" } ``` ### Response #### Success Response (200) * **music** (muspy.Music) - Loaded Music object. #### Response Example ```json { "music": "" } ``` ``` -------------------------------- ### Get Text from XML Element Source: https://github.com/salu133445/muspy/blob/main/docs/_modules/muspy/inputs/musicxml.html Safely retrieves text content from an XML element at a specified path. It allows for an optional default value if the element or its text is not found. Can also remove newline characters from the text. ```python def _get_text(element: Element, path: str, default: T = None, remove_newlines: bool = False) -> Union[str, T]: """Return the text of the first matching element.""" elem = element.find(path) if elem is not None and elem.text is not None: if remove_newlines: return " ".join(elem.text.splitlines()) return elem.text return default # type: ignore ```