ms3 package

Submodules

ms3.bs4_measures module

class ms3.bs4_measures.MeasureList(df, section_breaks=True, secure=False, reset_index=True, logger_name='MeasureList', level=None)[source]

Bases: object

Turns a _MSCX_bs4._measures DataFrame into a measure list and performs a couple of consistency checks on the score.

df

The input DataFrame from _MSCX_bs4.raw_measures

Type

pandas.DataFrame

section_breaks

By default, section breaks allow for several anacrusis measures within the piece (relevant for mc_offset column) and make it possible to omit a repeat sign in the following bar (relevant for next column). Set to False if you want to ignore section breaks.

Type

bool, default True

secure

By default, measure information from lower staves is considered to contain only redundant information. Set to True if you want to be warned about additional measure information from lower staves that is not taken into account.

Type

bool, default False

reset_index

By default, the original index of df is replaced. Pass False to keep original index values.

Type

bool, default True

logger_name

If you have defined a logger, pass its name.

Type

str, optional

level

Pass a level name for which (and above which) you want to see log records.

Type

{‘W’, ‘D’, ‘I’, ‘E’, ‘C’, ‘WARNING’, ‘DEBUG’, ‘INFO’, ‘ERROR’, ‘CRITICAL’}, optional

cols

Dictionary of the relevant columns in df as present after the parse.

Type

dict

ml

The measure list in the making; the final result.

Type

pandas.DataFrame

volta_structure

Keys are first MCs of volta groups, values are dictionaries of {volta_no: [mc1, mc2 …]}

Type

dict

make_ml(section_breaks=True, secure=False, reset_index=True, logger_name=None, level=None)[source]
add_col(func, **kwargs)[source]

Inserts or appends a column created by func(df, **kwargs)

get_unique_measure_list(**kwargs)[source]

Keep only the measure information from the first staff. Uses: keep_one_row_each()

Parameters
  • mc_col (str, optional) – DataFrame columns where MC and staff can be found. Staff is to be dropped.

  • staff_col (str, optional) – DataFrame columns where MC and staff can be found. Staff is to be dropped.

  • secure (bool) – If the dropped rows contain additional information, set secure to True to be informed about the information being lost by the function keep_one_row_each().

  • **kwargs (Additional parameter passed on to keep_one_row_each(). Ignored if secure=False.) –

check_measure_numbers(mc_col='mc', mn_col='mn', act_dur='act_dur', mc_offset='mc_offset', dont_count='dont_count', numbering_offset='numbering_offset')[source]
class ms3.bs4_measures.NextColumnMaker(mc, volta_structure, logger=None)[source]

Bases: object

start_section(mc)[source]
end_section(mc)[source]
treat_input(mc, repeat, section_break=False)[source]
ms3.bs4_measures.get_volta_structure(df, mc, volta_start, volta_length, frac_col=None)[source]

Uses: treat_group()

ms3.bs4_measures.keep_one_row_each(df, compress_col, differentiating_col, differentiating_val=None, ignore_columns=None, fillna=True, drop_differentiating=True)[source]
Eliminates duplicates in compress_col but warns about values within the

dropped rows which diverge from those of the remaining rows. The differentiating_col serves to identify places where information gets lost during the process.

The result of this function is the same as df.drop_duplicates(subset=[compress_col]) if differentiating_val is None, and df[df[compress_col] == differentiating_val] otherwise but with the difference that only adjacent duplicates are eliminated.

Parameters
  • compress_col (str) – Column with duplicates (e.g. measure counts).

  • differentiating_col (str) – Column that differentiates duplicates (e.g. staff IDs).

  • differentiating_val (value, optional) – If you want to keep rows with a certain differentiating_col value, pass that value (e.g. a certain staff). Otherwise, the first row of every compress_col value is kept.

  • ignore_columns (Iterable, optional) – These columns are not checked.

  • fillna (bool, optional) – By default, missing values of kept rows are filled if the dropped rows contain one unique value in that particular column. Pass False to keep rows as they are.

  • drop_differentiating (bool, optional) – By default, the column that differentiates the compress_col is dropped. Pass False to prevent that.

ms3.bs4_measures.make_actdur_col(df, len_col, timesig_col='timesig', name='act_dur')[source]
ms3.bs4_measures.make_keysig_col(df, keysig_col, name='keysig')[source]
ms3.bs4_measures.make_mn_col(df, dont_count, numbering_offset, name='mn')[source]

Compute measure numbers where one or two columns can influence the counting.

Parameters
  • df (pd.DataFrame) – If no other parameters are given, every row is counted, starting from 1.

  • dont_count (str, optional) – This column has notna() for measures where the option “Exclude from bar count” is activated, NaN otherwise.

  • numbering_offset (str, optional) – This column has values of the MuseScore option “Add to bar number”, which adds notna() values to this and all subsequent measures.

ms3.bs4_measures.make_next_col(df, mc_col='mc', repeats='repeats', volta_structure={}, section_breaks=None, name='next')[source]

Uses a NextColumnMaker object to create a column with all MCs that can follow each MC (e.g. due to repetitions).

Parameters
  • df (pandas.DataFrame) – Raw measure list.

  • mc_col (str, optional) – Column names.

  • repeats (str, optional) – Column names.

  • volta_structure (dict, optional) – This parameter can be computed by get_volta_structure(). It is empty if there are no voltas in the piece.

  • section_breaks (str, optional) – If you pass the name of a column, the string ‘section’ is taken into account as ending a section and therefore potentially ending a repeated part even when the repeat sign is missing.

ms3.bs4_measures.make_offset_col(df, mc_col='mc', timesig='timesig', act_dur='act_dur', next_col='next', section_breaks=None, name='mc_offset')[source]

If one MN is composed of two MCs, the resulting column indicates the second MC’s offset from the MN’s beginning.

Parameters
  • mc_col (str, optional) – Names of the required columns.

  • timesig (str, optional) – Names of the required columns.

  • act_dur (str, optional) – Names of the required columns.

  • next_col (str, optional) – Names of the required columns.

  • section_breaks (str, optional) – If you pass the name of a column, the string ‘section’ is taken into account as ending a section and therefore potentially ending a repeated part even when the repeat sign is missing.

ms3.bs4_measures.make_repeat_col(df, startRepeat, endRepeat, name='repeats')[source]
ms3.bs4_measures.make_timesig_col(df, sigN_col, sigD_col, name='timesig')[source]
ms3.bs4_measures.make_volta_col(df, volta_structure, mc='mc', name='volta')[source]

Create the input for volta_structure using get_volta_structure()

ms3.bs4_measures.treat_group(mc, group)[source]

Helper function for make_volta_col() Input example: array([[93, 1, 1], [94, 2, 2], [96, 3, 1]]) where columns are (MC, volta number, volta length).

ms3.bs4_parser module

ms3.bs4_parser.get_duration_event(elements)[source]
ms3.bs4_parser.make_spanner_cols(df, spanner_types=None)[source]
From a raw chord list as returned by get_chords(spanners=True)

create a DataFrame with Spanner IDs for all chords for all spanner types they are associated with.

Parameters

spanner_types (collection) – If this parameter is passed, only the enlisted spanner types (e.g. Slur or Pedal) are included.

ms3.bs4_parser.sort_note_list(df, mc_col='mc', onset_col='onset', midi_col='midi', duration_col='duration')[source]

Sort every measure (MC) by [‘onset’, ‘midi’, ‘duration’] while leaving gracenotes’ order (duration=0) intact

ms3.bs4_parser.make_tied_col(df, tie_col, next_col, prev_col)[source]
ms3.bs4_parser.safe_update(old, new)[source]

Update dict without replacing values.

ms3.bs4_parser.recurse_node(node, prepend=None, exclude_children=None)[source]
ms3.bs4_parser.sort_cols(df, first_cols=None)[source]
ms3.bs4_parser.bs4_chord_duration(node, duration_multiplier=1)[source]
ms3.bs4_parser.bs4_rest_duration(node, duration_multiplier=1)[source]
ms3.bs4_parser.opening_tag(node, closed=False)[source]
ms3.bs4_parser.closing_tag(node_name)[source]
ms3.bs4_parser.make_oneliner(node)[source]
ms3.bs4_parser.bs4_to_mscx(soup)[source]

ms3.logger module

class ms3.logger.ContextAdapter(logger, extra)[source]

Bases: logging.LoggerAdapter

This LoggerAdapter is designed to include the module and function that called the logger.

process(msg, overwrite={}, stack_info=False, **kwargs)[source]

Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs.

Normally, you’ll only need to override this one method in a LoggerAdapter subclass for your specific needs.

ms3.logger.get_logger(name=None, level=None, adapter=<class 'ms3.logger.ContextAdapter'>)[source]

The function gets or creates the logger name and returns it, by default through the given LoggerAdapter class.

ms3.logger.config_logger(name, level=None, logfile=None)[source]

Configs the logger with name name. Overwrites existing config.

ms3.logger.function_logger(f)[source]
This decorator ensures that the decorated function can use the variable logger for logging and

makes it possible to pass the function the keyword argument logger with either a Logger object or the name of one. If the keyword argument is not passed, the root logger is used.

Example

This is how the decorator can be used:

from ms3.logger import function_logger

@function_logger
def log_this(msg):
    logger.warning(msg)

if __name__ == '__main__':
    log_this('First test', logger='my_logger')
    log_this('Second Test')

Output:

WARNING my_logger -- function_logger.py (line 5) log_this():
    First test
WARNING root -- function_logger.py (line 5) log_this():
    Second Test

ms3.score module

class ms3.score.Score(mscx_src=None, infer_label_types=['dcml'], read_only=False, logger_name='Score', level=None, parser='bs4')[source]

Bases: object

Object representing a score.

infer_label_types

Changing this value results in a call to infer_types().

Type

list or dict, optional

logger

Current logger that the object is using.

Type

logging.Logger or logging.LoggerAdapter

parser

The only XML parser currently implemented is BeautifulSoup 4.

Type

{‘bs4’}

paths, files, fnames, fexts, logger_names

Dictionaries for keeping track of file information handled by handle_path().

Type

dict

_annotations
_harmony_regex
_label_types
_mscx

After parsing, holds the MSCX object with the parsed score.

Type

MSCX

_types_to_infer
handle_path(path, key)[source]

Puts the path into paths, files, fnames, fexts dicts with the given key.

abs_regex = '^\\(?[A-G|a-g](b*|#*).*?(/[A-G|a-g](b*|#*))?$'
dcml_regex = re.compile('\n ^(?P<first>\n (\\.?\n ((?P<globalkey>[a-gA-G](b*|\\#*))\\.)?\n , re.VERBOSE)
nashville_regex = '^(b*|#*)(\\d).*$'
rn_regex = '^$'
property infer_label_types
get_infer_regex()[source]
handle_path(path, key=None)[source]
output_mscx(filepath)[source]
detach_labels(key, staff=None, voice=None, label_type=None, delete=True)[source]
attach_labels(key, staff=None, voice=None)[source]
property mscx

Returns the MSCX object with the parsed score.

load_annotations(tsv_path, key='file', infer=True)[source]
store_annotations(key=None, tsv_path=None, **kwargs)[source]
property types
new_type(name, regex, description='', infer=True)[source]
class ms3.score.MSCX(mscx_src=None, read_only=False, parser='bs4', logger_name='MSCX', level=None)[source]

Bases: object

Object for interacting with the XML structure of a MuseScore 3 file.

mscx_src

MuseScore 3 file to parse.

Type

str

_parsed

Holds the MSCX score parsed by the selected parser.

Type

_MSCX_bs4

parser

Which XML parser to use.

Type

str, optional

infer_label_types :obj:`bool`, optional

For label_type 0 (simple string), mark which ones

logger_name

If you have defined a logger, pass its name.

Type

str, optional

level

Pass a level name for which (and above which) you want to see log records.

Type

{‘W’, ‘D’, ‘I’, ‘E’, ‘C’, ‘WARNING’, ‘DEBUG’, ‘INFO’, ‘ERROR’, ‘CRITICAL’}, optional

output_mscx(filepath)

Write the internal score representation to a file.

parse_mscx(mscx_src=None)[source]
delete_labels(df)[source]
add_labels(df, label='label', mc='mc', onset='onset', staff='staff', voice='voice', **kwargs)[source]
Parameters
  • df (pandas.DataFrame) – DataFrame with labels to be added.

  • label (str) – Names of the DataFrame columns for the five required parameters.

  • mc (str) – Names of the DataFrame columns for the five required parameters.

  • onset (str) – Names of the DataFrame columns for the five required parameters.

  • staff (str) – Names of the DataFrame columns for the five required parameters.

  • voice (str) – Names of the DataFrame columns for the five required parameters.

  • kwargs

    label_type, root, base, leftParen, rightParen, offset_x, offset_y, nashville

    For these parameters, the standard column names are used automatically if the columns are present. If the column names have changed, pass them as kwargs, e.g. base='name_of_the_base_column'

Returns

Return type

None

property parsed
property measures
property events
property chords
property labels
property notes
property rests
property notes_and_rests
property expanded
property version

MuseScore version with which the file was created (read-only).

ms3.skeleton module

This is a skeleton file that can serve as a starting point for a Python console script. To run this script uncomment the following lines in the [options.entry_points] section in setup.cfg:

console_scripts =

fibonacci = ms3.skeleton:run

Then run python setup.py install which will install the command fibonacci inside your current environment. Besides console scripts, the header (i.e. until _logger…) of this file can also be used as template for Python modules.

Note: This skeleton file can be safely removed if not needed!

ms3.skeleton.fib(n)[source]

Fibonacci example function

Parameters

n (int) – integer

Returns

n-th Fibonacci number

Return type

int

ms3.skeleton.parse_args(args)[source]

Parse command line parameters

Parameters

args ([str]) – command line parameters as list of strings

Returns

command line parameters namespace

Return type

argparse.Namespace

ms3.skeleton.setup_logging(loglevel)[source]

Setup basic logging

Parameters

loglevel (int) – minimum loglevel for emitting messages

ms3.skeleton.main(args)[source]

Main entry point allowing external calls

Parameters

args ([str]) – command line parameter list

ms3.skeleton.run()[source]

Entry point for console_scripts

class ms3.skeleton.score[source]

Bases: object

ms3.transformations module

Module contents

All functionality of the library is available through creating a ms3.Score object for a single score and a ms3.Parse object for multiple scores. Parsing a list of annotation labels only can be done by creating a ms3.Annotations object.